Example usage for org.bouncycastle.crypto.engines AESWrapEngine AESWrapEngine

List of usage examples for org.bouncycastle.crypto.engines AESWrapEngine AESWrapEngine

Introduction

In this page you can find the example usage for org.bouncycastle.crypto.engines AESWrapEngine AESWrapEngine.

Prototype

public AESWrapEngine() 

Source Link

Document

Create a regular AESWrapEngine specifying the encrypt for wrapping, decrypt for unwrapping.

Usage

From source file:com.geoxp.oss.CryptoHelper.java

License:Apache License

/**
 * Protect some data using AES Key Wrapping
 * //from   www.  j  a va 2s. c  om
 * @param key AES wrapping key
 * @param data Data to wrap
 * @param offset Where does the data start in 'data'
 * @param len How long is the data
 * @param nonce Should a random prefix be added to the data prior to wrapping
 * @return The wrapped data
 */
public static byte[] wrapAES(byte[] key, byte[] data, int offset, int len, boolean nonce) {

    //
    // Initialize AES Wrap Engine for wrapping
    //

    AESWrapEngine aes = new AESWrapEngine();
    KeyParameter keyparam = new KeyParameter(key);
    aes.init(true, keyparam);

    if (nonce) {
        byte[] nonced = new byte[len + OSS.NONCE_BYTES];
        byte[] noncebytes = new byte[OSS.NONCE_BYTES];
        getSecureRandom().nextBytes(noncebytes);
        System.arraycopy(noncebytes, 0, nonced, 0, OSS.NONCE_BYTES);
        System.arraycopy(data, offset, nonced, OSS.NONCE_BYTES, len);
        data = nonced;
        offset = 0;
        len = data.length;
    }

    //
    // Pad the data on an 8 bytes boundary
    //

    byte[] padded = padPKCS7(8, data, offset, len);

    //
    // Wrap data and return it
    //

    return aes.wrap(padded, 0, padded.length);
}

From source file:com.geoxp.oss.CryptoHelper.java

License:Apache License

/**
 * Unwrap data protected by AES Key Wrapping
 * //from  w w w  .  j av  a  2 s  . c  o  m
 * @param key Key used to wrap the data
 * @param data Wrapped data
 * @return The unwrapped data or null if an error occurred
 */
public static byte[] unwrapAES(byte[] key, byte[] data, boolean hasnonce) {

    //
    // Initialize the AES Wrap Engine for unwrapping
    //

    AESWrapEngine aes = new AESWrapEngine();
    KeyParameter keyparam = new KeyParameter(key);
    aes.init(false, keyparam);

    //
    // Unwrap then unpad data
    //

    try {
        byte[] unpadded = unpadPKCS7(aes.unwrap(data, 0, data.length));

        //
        // Remove nonce if data has one
        //

        if (hasnonce) {
            return Arrays.copyOfRange(unpadded, OSS.NONCE_BYTES, unpadded.length);
        } else {
            return unpadded;
        }
    } catch (InvalidCipherTextException icte) {
        return null;
    }
}

From source file:com.skplanet.jose.jwa.crypto.CryptoUtils.java

License:Open Source License

public static byte[] KeyWrap(Transformation transformation, byte[] symmetricKey, byte[] cek) {
    AESWrapEngine engine = new AESWrapEngine();
    CipherParameters param = new KeyParameter(
            new SecretKeySpec(symmetricKey, transformation.getAlgorithm()).getEncoded());
    engine.init(true, param);//from  w ww  .j a  va 2 s . co m
    return engine.wrap(cek, 0, cek.length);
}

From source file:com.skplanet.jose.jwa.crypto.CryptoUtils.java

License:Open Source License

public static byte[] keyUnwrap(Transformation transformation, byte[] symmetricKey, byte[] cek)
        throws Exception {
    AESWrapEngine engine = new AESWrapEngine();
    CipherParameters param = new KeyParameter(
            new SecretKeySpec(symmetricKey, transformation.getAlgorithm()).getEncoded());
    engine.init(false, param);/*from   w  w  w  .  j ava2  s  .  com*/
    return engine.unwrap(cek, 0, cek.length);
}

From source file:COSE.Recipient.java

private byte[] AES_KeyWrap_Encrypt(AlgorithmID alg, byte[] rgbKey) throws CoseException {
    if (rgbKey.length != alg.getKeySize() / 8)
        throw new CoseException("Key is not the correct size");

    AESWrapEngine foo = new AESWrapEngine();
    KeyParameter parameters = new KeyParameter(rgbKey);
    foo.init(true, parameters);//from  w  ww . j  av a 2s.com
    return foo.wrap(rgbContent, 0, rgbContent.length);
}

From source file:COSE.Recipient.java

private byte[] AES_KeyWrap_Decrypt(AlgorithmID alg, byte[] rgbKey)
        throws CoseException, InvalidCipherTextException {
    if (rgbKey.length != alg.getKeySize() / 8)
        throw new CoseException("Key is not the correct size");

    AESWrapEngine foo = new AESWrapEngine();
    KeyParameter parameters = new KeyParameter(rgbKey);
    foo.init(false, parameters);/*w  w  w .  j av a2  s.c o m*/
    return foo.unwrap(rgbEncrypted, 0, rgbEncrypted.length);
}

From source file:io.warp10.continuum.gts.CustomBufferBasedGTSDecoder.java

License:Apache License

/**
 * Attempt to read the next measurement and associated metadata (timestamp, location, elevation)
 * @return true if a measurement was successfully read, false if none were left in the buffer.
 *//*from w w w .  j a  v  a 2 s .c  o m*/
public boolean next() {

    //
    // Update position prior to reading the next value, etc so we can 
    //

    this.position = this.buffer.position();

    if (!buffer.hasRemaining()) {
        return false;
    }

    this.nextCalled = true;

    //
    // Read timestamp/type flag
    //

    byte tsTypeFlag = buffer.get();

    //
    // Check if we encountered encrypted data
    //

    if (GTSEncoder.FLAGS_ENCRYPTED == (tsTypeFlag & GTSEncoder.FLAGS_MASK_ENCRYPTED)) {
        //
        // Extract encrypted length
        //

        int enclen = (int) Varint.decodeUnsignedLong(buffer);

        //
        // If there is no decryption key, simply skip the encrypted data
        // and call next recursively.
        //

        if (null == wrappingKey) {
            buffer.position(buffer.position() + enclen);

            // WARNING(hbs): if there are many encrypted chunks this may lead to a stack overflow
            return next();
        }

        byte[] encrypted = new byte[enclen];
        buffer.get(encrypted);

        //
        // Decrypt the encrypted data
        //

        AESWrapEngine engine = new AESWrapEngine();
        CipherParameters params = new KeyParameter(this.wrappingKey);
        engine.init(false, params);

        try {
            byte[] decrypted = engine.unwrap(encrypted, 0, encrypted.length);
            //
            // Unpad the decrypted data
            //

            PKCS7Padding padding = new PKCS7Padding();
            int padcount = padding.padCount(decrypted);

            //
            // Replace the current buffer with a new one containing the
            // decrypted data followed by any remaining data in the original
            // buffer.
            //

            this.buffer.insert(decrypted, 0, decrypted.length - padcount);
        } catch (InvalidCipherTextException icte) {
            // FIXME(hbs): log this somewhere...
            //
            // Skip the encrypted chunk we failed to decrypt
            //
        }

        //
        // Call next recursively
        //
        // WARNING(hbs): we may hit StackOverflow in some cases

        return next();
    }

    //
    // Read location/elevation flag if needed
    //

    byte locElevFlag = 0x0;

    if (GTSEncoder.FLAGS_CONTINUATION == (tsTypeFlag & GTSEncoder.FLAGS_CONTINUATION)) {
        if (!buffer.hasRemaining()) {
            return false;
        }

        locElevFlag = buffer.get();
    }

    //
    // Read timestamp
    //

    switch (tsTypeFlag & GTSEncoder.FLAGS_MASK_TIMESTAMP) {
    case GTSEncoder.FLAGS_TIMESTAMP_RAW_ABSOLUTE: {
        ByteOrder order = buffer.order();
        buffer.order(ByteOrder.BIG_ENDIAN);
        previousLastTimestamp = lastTimestamp;
        lastTimestamp = buffer.getLong();
        buffer.order(order);
    }
        break;
    //case GTSEncoder.FLAGS_TIMESTAMP_ZIGZAG_ABSOLUTE:
    //  previousLastTimestamp = lastTimestamp;
    //  lastTimestamp = Varint.decodeSignedLong(buffer);
    //  break;
    case GTSEncoder.FLAGS_TIMESTAMP_EQUALS_BASE:
        previousLastTimestamp = lastTimestamp;
        lastTimestamp = baseTimestamp;
        break;
    case GTSEncoder.FLAGS_TIMESTAMP_ZIGZAG_DELTA_BASE: {
        long delta = Varint.decodeSignedLong(buffer);
        previousLastTimestamp = lastTimestamp;
        lastTimestamp = baseTimestamp + delta;
    }
        break;
    case GTSEncoder.FLAGS_TIMESTAMP_ZIGZAG_DELTA_PREVIOUS: {
        long delta = Varint.decodeSignedLong(buffer);
        previousLastTimestamp = lastTimestamp;
        lastTimestamp = lastTimestamp + delta;
    }
        break;
    default:
        throw new RuntimeException("Invalid timestamp format.");
    }

    //
    // Read location/elevation
    //

    if (GTSEncoder.FLAGS_LOCATION == (locElevFlag & GTSEncoder.FLAGS_LOCATION)) {
        if (GTSEncoder.FLAGS_LOCATION_IDENTICAL != (locElevFlag & GTSEncoder.FLAGS_LOCATION_IDENTICAL)) {
            if (GTSEncoder.FLAGS_LOCATION_GEOXPPOINT_ZIGZAG_DELTA == (locElevFlag
                    & GTSEncoder.FLAGS_LOCATION_GEOXPPOINT_ZIGZAG_DELTA)) {
                long delta = Varint.decodeSignedLong(buffer);
                previousLastGeoXPPoint = lastGeoXPPoint;
                lastGeoXPPoint = lastGeoXPPoint + delta;
            } else {
                ByteOrder order = buffer.order();
                buffer.order(ByteOrder.BIG_ENDIAN);
                previousLastGeoXPPoint = lastGeoXPPoint;
                lastGeoXPPoint = buffer.getLong();
                buffer.order(order);
            }
        }
    } else {
        previousLastGeoXPPoint = lastGeoXPPoint;
        lastGeoXPPoint = GeoTimeSerie.NO_LOCATION;
    }

    if (GTSEncoder.FLAGS_ELEVATION == (locElevFlag & GTSEncoder.FLAGS_ELEVATION)) {
        if (GTSEncoder.FLAGS_ELEVATION_IDENTICAL != (locElevFlag & GTSEncoder.FLAGS_ELEVATION_IDENTICAL)) {
            boolean zigzag = GTSEncoder.FLAGS_ELEVATION_ZIGZAG == (locElevFlag
                    & GTSEncoder.FLAGS_ELEVATION_ZIGZAG);

            long encoded;

            if (zigzag) {
                encoded = Varint.decodeSignedLong(buffer);
            } else {
                ByteOrder order = buffer.order();
                buffer.order(ByteOrder.BIG_ENDIAN);
                encoded = buffer.getLong();
                buffer.order(order);
            }

            if (GTSEncoder.FLAGS_ELEVATION_DELTA_PREVIOUS == (locElevFlag
                    & GTSEncoder.FLAGS_ELEVATION_DELTA_PREVIOUS)) {
                previousLastElevation = lastElevation;
                lastElevation = lastElevation + encoded;
            } else {
                previousLastElevation = lastElevation;
                lastElevation = encoded;
            }
        }
    } else {
        previousLastElevation = lastElevation;
        lastElevation = GeoTimeSerie.NO_ELEVATION;
    }

    //
    // Extract value
    //

    switch (tsTypeFlag & GTSEncoder.FLAGS_MASK_TYPE) {
    case GTSEncoder.FLAGS_TYPE_LONG:
        lastType = TYPE.LONG;
        if (GTSEncoder.FLAGS_VALUE_IDENTICAL != (tsTypeFlag & GTSEncoder.FLAGS_VALUE_IDENTICAL)) {
            long encoded;

            if (GTSEncoder.FLAGS_LONG_ZIGZAG == (tsTypeFlag & GTSEncoder.FLAGS_LONG_ZIGZAG)) {
                encoded = Varint.decodeSignedLong(buffer);
            } else {
                ByteOrder order = buffer.order();
                buffer.order(ByteOrder.BIG_ENDIAN);
                encoded = buffer.getLong();
                buffer.order(order);
            }

            if (GTSEncoder.FLAGS_LONG_DELTA_PREVIOUS == (tsTypeFlag & GTSEncoder.FLAGS_LONG_DELTA_PREVIOUS)) {
                previousLastLongValue = lastLongValue;
                lastLongValue = lastLongValue + encoded;
            } else {
                previousLastLongValue = lastLongValue;
                lastLongValue = encoded;
            }
        }
        break;

    case GTSEncoder.FLAGS_TYPE_DOUBLE:
        lastType = TYPE.DOUBLE;
        if (GTSEncoder.FLAGS_VALUE_IDENTICAL != (tsTypeFlag & GTSEncoder.FLAGS_VALUE_IDENTICAL)) {
            if (GTSEncoder.FLAGS_DOUBLE_IEEE754 == (tsTypeFlag & GTSEncoder.FLAGS_DOUBLE_IEEE754)) {
                ByteOrder order = buffer.order();
                buffer.order(ByteOrder.BIG_ENDIAN);
                previousLastDoubleValue = lastDoubleValue;
                lastDoubleValue = buffer.getDouble();
                previousLastBDValue = lastBDValue;
                lastBDValue = null;
                buffer.order(order);
            } else {
                int scale = buffer.get();
                long unscaled = Varint.decodeSignedLong(buffer);
                previousLastBDValue = lastBDValue;
                lastBDValue = new BigDecimal(new BigInteger(Long.toString(unscaled)), scale);
            }
        }
        break;

    case GTSEncoder.FLAGS_TYPE_STRING:
        lastType = TYPE.STRING;
        if (GTSEncoder.FLAGS_VALUE_IDENTICAL != (tsTypeFlag & GTSEncoder.FLAGS_VALUE_IDENTICAL)) {
            // Decode String length
            long len = Varint.decodeUnsignedLong(buffer);

            // Prevent excessive allocation
            if (len > buffer.remaining()) {
                throw new RuntimeException("Invalid string length.");
            }

            byte[] utf8 = new byte[(int) len];
            // Read String UTF8 representation
            buffer.get(utf8);
            previousLastStringValue = lastStringValue;
            lastStringValue = new String(utf8, Charsets.UTF_8);
        }
        break;

    case GTSEncoder.FLAGS_TYPE_BOOLEAN:
        if (GTSEncoder.FLAGS_DELETE_MARKER == (tsTypeFlag & GTSEncoder.FLAGS_MASK_TYPE_FLAGS)) {
            lastType = TYPE.UNDEFINED;
        } else {
            lastType = TYPE.BOOLEAN;

            if (GTSEncoder.FLAGS_BOOLEAN_VALUE_TRUE == (tsTypeFlag & GTSEncoder.FLAGS_MASK_TYPE_FLAGS)) {
                lastBooleanValue = true;
            } else if (GTSEncoder.FLAGS_BOOLEAN_VALUE_FALSE == (tsTypeFlag
                    & GTSEncoder.FLAGS_MASK_TYPE_FLAGS)) {
                lastBooleanValue = false;
            } else {
                throw new RuntimeException("Invalid boolean value.");
            }
            //lastBooleanValue = GTSEncoder.FLAGS_BOOLEAN_VALUE == (tsTypeFlag & GTSEncoder.FLAGS_BOOLEAN_VALUE);
        }
        break;

    default:
        throw new RuntimeException("Invalid type encountered!");
    }

    return true;
}

From source file:io.warp10.continuum.gts.GTSDecoder.java

License:Apache License

/**
 * Attempt to read the next measurement and associated metadata (timestamp, location, elevation)
 * @return true if a measurement was successfully read, false if none were left in the buffer.
 *///from  w  w w .j a v a2 s  .  co  m
public boolean next() {

    //
    // Update position prior to reading the next value, etc so we can 
    //

    this.position = this.buffer.position();

    if (!buffer.hasRemaining()) {
        return false;
    }

    this.nextCalled = true;

    //
    // Read timestamp/type flag
    //

    byte tsTypeFlag = buffer.get();

    //
    // Check if we encountered encrypted data
    //

    if (GTSEncoder.FLAGS_ENCRYPTED == (tsTypeFlag & GTSEncoder.FLAGS_MASK_ENCRYPTED)) {
        //
        // Extract encrypted length
        //

        int enclen = (int) Varint.decodeUnsignedLong(buffer);

        //
        // If there is no decryption key, simply skip the encrypted data
        // and call next recursively.
        //

        if (null == wrappingKey) {
            buffer.position(buffer.position() + enclen);

            // WARNING(hbs): if there are many encrypted chunks this may lead to a stack overflow
            return next();
        }

        byte[] encrypted = new byte[enclen];
        buffer.get(encrypted);

        //
        // Decrypt the encrypted data
        //

        AESWrapEngine engine = new AESWrapEngine();
        CipherParameters params = new KeyParameter(this.wrappingKey);
        engine.init(false, params);

        try {
            byte[] decrypted = engine.unwrap(encrypted, 0, encrypted.length);
            //
            // Unpad the decrypted data
            //

            PKCS7Padding padding = new PKCS7Padding();
            int padcount = padding.padCount(decrypted);

            //
            // Replace the current buffer with a new one containing the
            // decrypted data followed by any remaining data in the original
            // buffer.
            //

            ByteBuffer bb = ByteBuffer.allocate(decrypted.length - padcount + this.buffer.remaining());

            bb.put(decrypted, 0, decrypted.length - padcount);
            bb.put(this.buffer);
            bb.flip();

            this.buffer = bb;
            decodedEncrypted = true;
        } catch (InvalidCipherTextException icte) {
            // FIXME(hbs): log this somewhere...
            //
            // Skip the encrypted chunk we failed to decrypt
            //
        }

        //
        // Call next recursively
        //
        // WARNING(hbs): we may hit StackOverflow in some cases

        return next();
    }

    //
    // Read location/elevation flag if needed
    //

    byte locElevFlag = 0x0;

    if (GTSEncoder.FLAGS_CONTINUATION == (tsTypeFlag & GTSEncoder.FLAGS_CONTINUATION)) {
        if (!buffer.hasRemaining()) {
            return false;
        }

        locElevFlag = buffer.get();
    }

    //
    // Read timestamp
    //

    switch (tsTypeFlag & GTSEncoder.FLAGS_MASK_TIMESTAMP) {
    case GTSEncoder.FLAGS_TIMESTAMP_RAW_ABSOLUTE: {
        ByteOrder order = buffer.order();
        buffer.order(ByteOrder.BIG_ENDIAN);
        previousLastTimestamp = lastTimestamp;
        lastTimestamp = buffer.getLong();
        buffer.order(order);
    }
        break;
    //case GTSEncoder.FLAGS_TIMESTAMP_ZIGZAG_ABSOLUTE:
    //  previousLastTimestamp = lastTimestamp;
    //  lastTimestamp = Varint.decodeSignedLong(buffer);
    //  break;
    case GTSEncoder.FLAGS_TIMESTAMP_EQUALS_BASE:
        previousLastTimestamp = lastTimestamp;
        lastTimestamp = baseTimestamp;
        break;
    case GTSEncoder.FLAGS_TIMESTAMP_ZIGZAG_DELTA_BASE: {
        long delta = Varint.decodeSignedLong(buffer);
        previousLastTimestamp = lastTimestamp;
        lastTimestamp = baseTimestamp + delta;
    }
        break;
    case GTSEncoder.FLAGS_TIMESTAMP_ZIGZAG_DELTA_PREVIOUS: {
        long delta = Varint.decodeSignedLong(buffer);
        previousLastTimestamp = lastTimestamp;
        lastTimestamp = lastTimestamp + delta;
    }
        break;
    default:
        throw new RuntimeException("Invalid timestamp format.");
    }

    //
    // Read location/elevation
    //

    if (GTSEncoder.FLAGS_LOCATION == (locElevFlag & GTSEncoder.FLAGS_LOCATION)) {
        if (GTSEncoder.FLAGS_LOCATION_IDENTICAL != (locElevFlag & GTSEncoder.FLAGS_LOCATION_IDENTICAL)) {
            if (GTSEncoder.FLAGS_LOCATION_GEOXPPOINT_ZIGZAG_DELTA == (locElevFlag
                    & GTSEncoder.FLAGS_LOCATION_GEOXPPOINT_ZIGZAG_DELTA)) {
                long delta = Varint.decodeSignedLong(buffer);
                previousLastGeoXPPoint = lastGeoXPPoint;
                lastGeoXPPoint = lastGeoXPPoint + delta;
            } else {
                ByteOrder order = buffer.order();
                buffer.order(ByteOrder.BIG_ENDIAN);
                previousLastGeoXPPoint = lastGeoXPPoint;
                lastGeoXPPoint = buffer.getLong();
                buffer.order(order);
            }
        }
    } else {
        previousLastGeoXPPoint = lastGeoXPPoint;
        lastGeoXPPoint = GeoTimeSerie.NO_LOCATION;
    }

    if (GTSEncoder.FLAGS_ELEVATION == (locElevFlag & GTSEncoder.FLAGS_ELEVATION)) {
        if (GTSEncoder.FLAGS_ELEVATION_IDENTICAL != (locElevFlag & GTSEncoder.FLAGS_ELEVATION_IDENTICAL)) {
            boolean zigzag = GTSEncoder.FLAGS_ELEVATION_ZIGZAG == (locElevFlag
                    & GTSEncoder.FLAGS_ELEVATION_ZIGZAG);

            long encoded;

            if (zigzag) {
                encoded = Varint.decodeSignedLong(buffer);
            } else {
                ByteOrder order = buffer.order();
                buffer.order(ByteOrder.BIG_ENDIAN);
                encoded = buffer.getLong();
                buffer.order(order);
            }

            if (GTSEncoder.FLAGS_ELEVATION_DELTA_PREVIOUS == (locElevFlag
                    & GTSEncoder.FLAGS_ELEVATION_DELTA_PREVIOUS)) {
                previousLastElevation = lastElevation;
                lastElevation = lastElevation + encoded;
            } else {
                previousLastElevation = lastElevation;
                lastElevation = encoded;
            }
        }
    } else {
        previousLastElevation = lastElevation;
        lastElevation = GeoTimeSerie.NO_ELEVATION;
    }

    //
    // Extract value
    //

    switch (tsTypeFlag & GTSEncoder.FLAGS_MASK_TYPE) {
    case GTSEncoder.FLAGS_TYPE_LONG:
        lastType = TYPE.LONG;
        if (GTSEncoder.FLAGS_VALUE_IDENTICAL != (tsTypeFlag & GTSEncoder.FLAGS_VALUE_IDENTICAL)) {
            long encoded;

            if (GTSEncoder.FLAGS_LONG_ZIGZAG == (tsTypeFlag & GTSEncoder.FLAGS_LONG_ZIGZAG)) {
                encoded = Varint.decodeSignedLong(buffer);
            } else {
                ByteOrder order = buffer.order();
                buffer.order(ByteOrder.BIG_ENDIAN);
                encoded = buffer.getLong();
                buffer.order(order);
            }

            if (GTSEncoder.FLAGS_LONG_DELTA_PREVIOUS == (tsTypeFlag & GTSEncoder.FLAGS_LONG_DELTA_PREVIOUS)) {
                previousLastLongValue = lastLongValue;
                lastLongValue = lastLongValue + encoded;
            } else {
                previousLastLongValue = lastLongValue;
                lastLongValue = encoded;
            }
        } else {
            previousLastLongValue = lastLongValue;
        }
        break;

    case GTSEncoder.FLAGS_TYPE_DOUBLE:
        lastType = TYPE.DOUBLE;
        if (GTSEncoder.FLAGS_VALUE_IDENTICAL != (tsTypeFlag & GTSEncoder.FLAGS_VALUE_IDENTICAL)) {
            if (GTSEncoder.FLAGS_DOUBLE_IEEE754 == (tsTypeFlag & GTSEncoder.FLAGS_DOUBLE_IEEE754)) {
                ByteOrder order = buffer.order();
                buffer.order(ByteOrder.BIG_ENDIAN);
                previousLastDoubleValue = lastDoubleValue;
                lastDoubleValue = buffer.getDouble();
                previousLastBDValue = lastBDValue;
                lastBDValue = null;
                buffer.order(order);
            } else {
                int scale = buffer.get();
                long unscaled = Varint.decodeSignedLong(buffer);
                previousLastBDValue = lastBDValue;
                lastBDValue = new BigDecimal(new BigInteger(Long.toString(unscaled)), scale);
            }
        } else {
            previousLastDoubleValue = lastDoubleValue;
            previousLastBDValue = lastBDValue;
        }
        break;

    case GTSEncoder.FLAGS_TYPE_STRING:
        lastType = TYPE.STRING;
        if (GTSEncoder.FLAGS_VALUE_IDENTICAL != (tsTypeFlag & GTSEncoder.FLAGS_VALUE_IDENTICAL)) {
            // Decode String length
            long len = Varint.decodeUnsignedLong(buffer);

            // Prevent excessive allocation
            if (len > buffer.remaining()) {
                throw new RuntimeException("Invalid string length.");
            }

            byte[] utf8 = new byte[(int) len];
            // Read String UTF8 representation
            buffer.get(utf8);
            previousLastStringValue = lastStringValue;
            lastStringValue = new String(utf8, Charsets.UTF_8);
        } else {
            previousLastStringValue = lastStringValue;
        }
        break;

    case GTSEncoder.FLAGS_TYPE_BOOLEAN:
        if (GTSEncoder.FLAGS_DELETE_MARKER == (tsTypeFlag & GTSEncoder.FLAGS_MASK_TYPE_FLAGS)) {
            lastType = TYPE.UNDEFINED;
        } else {
            lastType = TYPE.BOOLEAN;

            if (GTSEncoder.FLAGS_BOOLEAN_VALUE_TRUE == (tsTypeFlag & GTSEncoder.FLAGS_MASK_TYPE_FLAGS)) {
                lastBooleanValue = true;
            } else if (GTSEncoder.FLAGS_BOOLEAN_VALUE_FALSE == (tsTypeFlag
                    & GTSEncoder.FLAGS_MASK_TYPE_FLAGS)) {
                lastBooleanValue = false;
            } else {
                throw new RuntimeException("Invalid boolean value.");
            }
            //lastBooleanValue = GTSEncoder.FLAGS_BOOLEAN_VALUE == (tsTypeFlag & GTSEncoder.FLAGS_BOOLEAN_VALUE);
        }
        break;

    default:
        throw new RuntimeException("Invalid type encountered!");
    }

    this.consumingNextCalls++;
    return true;
}

From source file:io.warp10.continuum.gts.GTSEncoder.java

License:Apache License

/**
 * Return the bytes currently in this encoder.
 * If 'wrappingKey' is non null, encrypt the bytes prior to returning them.
 * //from  w  w  w.j a  va  2  s .c  o m
 * @return The (possibly encrypted bytes) or null if an exception is raised
 *         while encrypting.
 * 
 */
public byte[] getBytes() {
    if (null == this.wrappingKey) {
        return this.stream.toByteArray();
    } else {
        AESWrapEngine engine = new AESWrapEngine();
        KeyParameter params = new KeyParameter(this.wrappingKey);
        engine.init(true, params);
        PKCS7Padding padding = new PKCS7Padding();
        byte[] unpadded = this.stream.toByteArray();

        //
        // Add padding
        //

        byte[] padded = new byte[unpadded.length + (8 - unpadded.length % 8)];
        System.arraycopy(unpadded, 0, padded, 0, unpadded.length);
        padding.addPadding(padded, unpadded.length);

        //
        // Wrap
        //

        byte[] encrypted = engine.wrap(padded, 0, padded.length);

        //
        // Add 0x0 flag and encrypted data size
        //

        ByteArrayOutputStream baos = new ByteArrayOutputStream();

        try {
            baos.write(GTSEncoder.FLAGS_ENCRYPTED);
            baos.write(Varint.encodeUnsignedLong(encrypted.length));
            baos.write(encrypted);
            return baos.toByteArray();
        } catch (IOException ioe) {
            return null;
        }
    }
}

From source file:io.warp10.continuum.gts.GTSEncoderTest.java

License:Apache License

@Test
public void testAddValue_encrypted() throws Exception {
    long now = System.currentTimeMillis() * 1000L;

    byte[] key = new byte[32];

    GTSEncoder encoder = new GTSEncoder(now - 1000000L, key);

    encoder.addValue(now, GeoTimeSerie.NO_LOCATION, GeoTimeSerie.NO_ELEVATION, 1L);
    encoder.addValue(now + 1000000L, GeoTimeSerie.NO_LOCATION, GeoTimeSerie.NO_ELEVATION, 2L);

    byte[] encrypted = encoder.getBytes();
    Assert.assertEquals(GTSEncoder.FLAGS_ENCRYPTED, encrypted[0] & GTSEncoder.FLAGS_MASK_ENCRYPTED);
    Assert.assertEquals(26, encrypted.length);

    ///*from  w w  w .j a  va2  s.c  om*/
    // Now check that we can decrypt the payload
    // We can't use n offset different than 0 in unwrap due to BJA-461
    // so we have to copy the data prior to decrypting it.
    //

    AESWrapEngine engine = new AESWrapEngine();
    KeyParameter params = new KeyParameter(key);
    engine.init(false, params);
    byte[] enc = new byte[24];
    System.arraycopy(encrypted, 2, enc, 0, 24);
    byte[] decrypted = engine.unwrap(enc, 0, 24);

    //
    // Now decode the decrypted data
    //

    PKCS7Padding padding = new PKCS7Padding();
    GTSDecoder decoder = new GTSDecoder(now - 1000000L,
            ByteBuffer.wrap(decrypted, 0, decrypted.length - padding.padCount(decrypted)));

    decoder.next();
    Assert.assertEquals(now, decoder.getTimestamp());
    Assert.assertEquals(GeoTimeSerie.NO_LOCATION, decoder.getLocation());
    Assert.assertEquals(GeoTimeSerie.NO_ELEVATION, decoder.getElevation());
    Assert.assertEquals(1L, decoder.getValue());

    decoder.next();
    Assert.assertEquals(now + 1000000L, decoder.getTimestamp());
    Assert.assertEquals(GeoTimeSerie.NO_LOCATION, decoder.getLocation());
    Assert.assertEquals(GeoTimeSerie.NO_ELEVATION, decoder.getElevation());
    Assert.assertEquals(2L, decoder.getValue());
}