Example usage for org.bouncycastle.crypto.paddings PKCS7Padding PKCS7Padding

List of usage examples for org.bouncycastle.crypto.paddings PKCS7Padding PKCS7Padding

Introduction

In this page you can find the example usage for org.bouncycastle.crypto.paddings PKCS7Padding PKCS7Padding.

Prototype

PKCS7Padding

Source Link

Usage

From source file:encryption.AESBouncyCastle.java

License:Open Source License

public static byte[] encrypt(byte[] key, byte[] input) throws DataLengthException, InvalidCipherTextException {
    pbbc = new PaddedBufferedBlockCipher(AESCipher, new PKCS7Padding());
    AESBouncyCastle.key = new KeyParameter(key);
    return processing(input, true);
}

From source file:encryption.AESBouncyCastle.java

License:Open Source License

public static byte[] decrypt(byte[] key, byte[] input) throws DataLengthException, InvalidCipherTextException {
    pbbc = new PaddedBufferedBlockCipher(AESCipher, new PKCS7Padding());
    AESBouncyCastle.key = new KeyParameter(key);
    return processing(input, false);
}

From source file:encryption.ThreefishBouncyCastle.java

License:Open Source License

public static byte[] encrypt(byte[] key, byte[] input) throws DataLengthException, InvalidCipherTextException {
    pbbc = new PaddedBufferedBlockCipher(ThreefishCipher, new PKCS7Padding());
    ThreefishBouncyCastle.key = new KeyParameter(key);
    return processing(input, true);
}

From source file:encryption.ThreefishBouncyCastle.java

License:Open Source License

public static byte[] decrypt(byte[] key, byte[] input) throws DataLengthException, InvalidCipherTextException {
    pbbc = new PaddedBufferedBlockCipher(ThreefishCipher, new PKCS7Padding());
    ThreefishBouncyCastle.key = new KeyParameter(key);
    return processing(input, false);
}

From source file:freemail.OutboundContact.java

License:Open Source License

/**
 * Set up an outbound contact. Fetch the mailsite, generate a new SSK keypair and post an RTS message to the appropriate KSK.
 * Will block for mailsite retrieval and RTS insertion
 *
 * @return true for success/*from  w  ww . j  a va 2s .  c o m*/
 */
private boolean init() throws ConnectionTerminatedException, InterruptedException {
    Logger.normal(this, "Initialising Outbound Contact " + address.toString());

    // try to fetch get all necessary info. will fetch mailsite / generate new keys if necessary
    String initialslot = this.getCurrentLowestSlot();
    SSKKeyPair commssk = this.getCommKeyPair();
    if (commssk == null)
        return false;
    SSKKeyPair ackssk = this.getAckKeyPair();
    RSAKeyParameters their_pub_key = this.getPubKey();
    if (their_pub_key == null)
        return false;
    String rtsksk = this.getRtsKsk();
    if (rtsksk == null)
        return false;

    StringBuffer rtsmessage = new StringBuffer();

    // the public part of the SSK keypair we generated
    rtsmessage.append("commssk=" + commssk.pubkey + "\r\n");

    rtsmessage.append("ackssk=" + ackssk.privkey + "\r\n");

    rtsmessage.append("initialslot=" + initialslot + "\r\n");

    rtsmessage.append("messagetype=rts\r\n");

    // must include who this RTS is to, otherwise we're vulnerable to surreptitious forwarding
    rtsmessage.append("to=" + this.address.getSubDomain() + "\r\n");

    // get our mailsite URI
    String our_mailsite_uri = account.getProps().get("mailsite.pubkey");

    rtsmessage.append("mailsite=" + our_mailsite_uri + "\r\n");

    rtsmessage.append("\r\n");
    //FreemailLogger.normal(this,rtsmessage.toString());

    // sign the message
    SHA256Digest sha256 = new SHA256Digest();
    sha256.update(rtsmessage.toString().getBytes(), 0, rtsmessage.toString().getBytes().length);
    byte[] hash = new byte[sha256.getDigestSize()];
    sha256.doFinal(hash, 0);

    RSAKeyParameters our_priv_key = AccountManager.getPrivateKey(account.getProps());

    AsymmetricBlockCipher sigcipher = new RSAEngine();
    sigcipher.init(true, our_priv_key);
    byte[] sig = null;
    try {
        sig = sigcipher.processBlock(hash, 0, hash.length);
    } catch (InvalidCipherTextException icte) {
        Logger.error(this, "Failed to RSA encrypt hash: " + icte.getMessage());
        icte.printStackTrace();
        return false;
    }

    ByteArrayOutputStream bos = new ByteArrayOutputStream();

    try {
        bos.write(rtsmessage.toString().getBytes());
        bos.write(sig);
    } catch (IOException ioe) {
        ioe.printStackTrace();
        return false;
    }

    // make up a symmetric key
    PaddedBufferedBlockCipher aescipher = new PaddedBufferedBlockCipher(new CBCBlockCipher(new AESEngine()),
            new PKCS7Padding());

    // quick paranoia check!
    if (aescipher.getBlockSize() != AES_BLOCK_LENGTH) {
        // bouncycastle must have changed their implementation, so 
        // we're in trouble
        Logger.normal(this,
                "Incompatible block size change detected in cryptography API! Are you using a newer version of the bouncycastle libraries? If so, we suggest you downgrade for now, or check for a newer version of Freemail.");
        return false;
    }

    byte[] aes_iv_and_key = this.getAESParams();

    // now encrypt that with our recipient's public key
    AsymmetricBlockCipher enccipher = new RSAEngine();
    enccipher.init(true, their_pub_key);
    byte[] encrypted_aes_params = null;
    try {
        encrypted_aes_params = enccipher.processBlock(aes_iv_and_key, 0, aes_iv_and_key.length);
    } catch (InvalidCipherTextException icte) {
        Logger.error(this,
                "Failed to perform asymmertic encryption on RTS symmetric key: " + icte.getMessage());
        icte.printStackTrace();
        return false;
    }

    // now encrypt the message with the symmetric key
    KeyParameter kp = new KeyParameter(aes_iv_and_key, aescipher.getBlockSize(), AES_KEY_LENGTH);
    ParametersWithIV kpiv = new ParametersWithIV(kp, aes_iv_and_key, 0, aescipher.getBlockSize());
    aescipher.init(true, kpiv);

    byte[] encmsg = new byte[aescipher.getOutputSize(bos.toByteArray().length) + encrypted_aes_params.length];
    System.arraycopy(encrypted_aes_params, 0, encmsg, 0, encrypted_aes_params.length);
    int offset = encrypted_aes_params.length;
    offset += aescipher.processBytes(bos.toByteArray(), 0, bos.toByteArray().length, encmsg, offset);

    try {
        aescipher.doFinal(encmsg, offset);
    } catch (InvalidCipherTextException icte) {
        Logger.error(this, "Failed to perform symmertic encryption on RTS data: " + icte.getMessage());
        icte.printStackTrace();
        return false;
    }

    // insert it!
    HighLevelFCPClient cli = new HighLevelFCPClient();
    if (cli.slotInsert(encmsg, "KSK@" + rtsksk + "-" + DateStringFactory.getKeyString(), 1, "") < 0) {
        // safe to copy the message into the contact outbox though
        return false;
    }

    // remember the fact that we have successfully inserted the rts
    this.contactfile.put("status", "rts-sent");
    // and remember when we sent it!
    this.contactfile.put("rts-sent-at", Long.toString(System.currentTimeMillis()));
    // and since that's been successfully inserted to that key, we can
    // throw away the symmetric key
    this.contactfile.remove("aesparams");

    Logger.normal(this, "Succesfully initialised Outbound Contact");

    return true;
}

From source file:freemail.RTSFetcher.java

License:Open Source License

private byte[] decrypt_rts(File rtsmessage) throws IOException, InvalidCipherTextException {
    // initialise our ciphers
    RSAKeyParameters ourprivkey = AccountManager.getPrivateKey(account.getProps());
    AsymmetricBlockCipher deccipher = new RSAEngine();
    deccipher.init(false, ourprivkey);/* ww  w  .j  a  v  a2 s .  com*/

    PaddedBufferedBlockCipher aescipher = new PaddedBufferedBlockCipher(new CBCBlockCipher(new AESEngine()),
            new PKCS7Padding());

    // first n bytes will be an encrypted RSA block containting the
    // AES IV and Key. Read that.
    byte[] encrypted_params = new byte[deccipher.getInputBlockSize()];
    FileInputStream fis = new FileInputStream(rtsmessage);
    int read = 0;

    while (read < encrypted_params.length) {
        read += fis.read(encrypted_params, read, encrypted_params.length - read);
        if (read < 0)
            break;
    }

    if (read < 0) {
        throw new InvalidCipherTextException("RTS Message too short");
    }

    byte[] aes_iv_and_key = deccipher.processBlock(encrypted_params, 0, encrypted_params.length);

    KeyParameter kp = new KeyParameter(aes_iv_and_key, aescipher.getBlockSize(),
            aes_iv_and_key.length - aescipher.getBlockSize());
    ParametersWithIV kpiv = new ParametersWithIV(kp, aes_iv_and_key, 0, aescipher.getBlockSize());
    try {
        aescipher.init(false, kpiv);
    } catch (IllegalArgumentException iae) {
        throw new InvalidCipherTextException(iae.getMessage());
    }

    byte[] plaintext = new byte[aescipher.getOutputSize((int) rtsmessage.length() - read)];

    int ptbytes = 0;
    while (read < rtsmessage.length()) {
        byte[] buf = new byte[(int) rtsmessage.length() - read];

        int thisread = fis.read(buf, 0, (int) rtsmessage.length() - read);
        ptbytes += aescipher.processBytes(buf, 0, thisread, plaintext, ptbytes);
        read += thisread;
    }

    fis.close();

    try {
        aescipher.doFinal(plaintext, ptbytes);
    } catch (DataLengthException dle) {
        throw new InvalidCipherTextException(dle.getMessage());
    }

    return plaintext;
}

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 ww.ja  v a  2s  .  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 .  ja  v  a  2s  .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.
            //

            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  v a  2s  .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);

    ///*  www  . j  av a  2s. c  o  m*/
    // 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());
}