Example usage for java.nio ByteBuffer array

List of usage examples for java.nio ByteBuffer array

Introduction

In this page you can find the example usage for java.nio ByteBuffer array.

Prototype

public final byte[] array() 

Source Link

Document

Returns the byte array which this buffer is based on, if there is one.

Usage

From source file:Main.java

static byte[] decryptJWE(String jwe, Key privRsaKey) {
    // Log.d("","decryptJWE");

    try {/*from  w  w  w.  j  av a  2 s .c  o m*/
        // split jwe string
        StringTokenizer tokens = new StringTokenizer(jwe, ".");
        int count = tokens.countTokens();
        // Log.d("","parts.length: "+count);

        if (count != 5)
            return null;

        String jweProtectedHeader64 = tokens.nextToken();
        String jweEncrypted64 = tokens.nextToken();
        String jweInitVector64 = tokens.nextToken();
        String cryptedBytes64 = tokens.nextToken();
        String auth_tag64 = tokens.nextToken();

        // decrypt cek using private rsa key
        byte[] cek = decryptRsaB64(jweEncrypted64, privRsaKey);

        // check cek result byte array
        if (cek == null || cek.length == 0 || (cek.length % 2) != 0)
            return null;

        int keySize = cek.length / 2;
        Log.d("", "Decryption AES: " + keySize * 8);

        // build aes_key and hmac_key
        byte aes_key[] = new byte[keySize];
        byte hmac_key[] = new byte[keySize];

        System.arraycopy(cek, 0, hmac_key, 0, keySize);
        System.arraycopy(cek, keySize, aes_key, 0, keySize);

        // decode initialization vector
        byte[] iv_key = decodeB64(jweInitVector64);

        Log.d("", "hmac_key: " + bytesToHex(hmac_key));
        Log.d("", "aes_key:  " + bytesToHex(aes_key));
        Log.d("", "iv_key:   " + bytesToHex(iv_key));

        // decrypt content using aes_key and iv_key
        byte[] cryptedBytes = decodeB64(cryptedBytes64);
        Cipher decrypt = Cipher.getInstance("AES/CBC/PKCS5Padding", "SC");
        decrypt.init(Cipher.DECRYPT_MODE, new SecretKeySpec(aes_key, "AES"), new IvParameterSpec(iv_key));
        byte[] decryptedBytes = decrypt.doFinal(cryptedBytes);

        Log.d("", "decryptedBytes:");
        Log.d("", bytesToHex(decryptedBytes));

        // validation verification
        byte[] aad = jweProtectedHeader64.getBytes();
        long al = aad.length * 8;

        // concatenate aad, iv_key, cryptedBytes and al 
        byte[] hmacData = new byte[aad.length + iv_key.length + cryptedBytes.length + 8];
        int offset = 0;
        System.arraycopy(aad, offset, hmacData, 0, aad.length);
        offset += aad.length;
        System.arraycopy(iv_key, 0, hmacData, offset, iv_key.length);
        offset += iv_key.length;
        System.arraycopy(cryptedBytes, 0, hmacData, offset, cryptedBytes.length);
        offset += cryptedBytes.length;
        ByteBuffer buffer = ByteBuffer.allocate(8);
        buffer.putLong(al);
        System.arraycopy(buffer.array(), 0, hmacData, offset, 8);

        // compute hmac
        Mac hmac = Mac.getInstance("HmacSHA256", "SC");
        hmac.init(new SecretKeySpec(hmac_key, "HmacSHA256"));
        byte[] hmacValue = hmac.doFinal(hmacData);

        // pick authentication tag
        byte[] authTag = Arrays.copyOf(hmacValue, 16);

        // validate authentication tag
        byte[] authTagRead = decodeB64(auth_tag64);
        for (int i = 0; i < 16; i++) {
            if (authTag[i] != authTagRead[i]) {
                Log.d("", "validation failed");
                return decryptedBytes;
            }
        }

        Log.d("", "validation success");

        // validation success
        return decryptedBytes;

    } catch (Exception e) {
        e.printStackTrace();
    }

    return null;
}

From source file:com.pushtechnology.diffusion.examples.runnable.RandomData.java

/**
 * Serialize a {@link RandomData} value as a {@link Binary} value.
 * @param randomData The {@link RandomData} value
 * @return The {@link Binary} value/*  w ww  .  ja v a  2  s .  c o  m*/
 */
static Binary toBinary(RandomData randomData) {
    final ByteBuffer buffer = ByteBuffer.allocate(16);
    buffer.putInt(randomData.getId());
    buffer.putLong(randomData.getTimestamp());
    buffer.putInt(randomData.getRandomInt());
    return Diffusion.dataTypes().binary().readValue(buffer.array());
}

From source file:org.brekka.phalanx.core.services.impl.AbstractCryptoService.java

private static byte[] encodeSecretKey(InternalSecretKeyToken iskt) {
    int profileId = iskt.getSymedCryptoData().getProfile();
    byte[] keyId = toBytes(iskt.getSymedCryptoData().getId());
    byte[] data = iskt.getSecretKey().getEncoded();
    ByteBuffer buffer = ByteBuffer.allocate(SK_MAGIC_MARKER.length + 20 + data.length).put(SK_MAGIC_MARKER)
            .putInt(profileId).put(keyId).put(data);
    return buffer.array();
}

From source file:com.all.shared.util.SyncUtils.java

public static String encodeAndZip(List<SyncEventEntity> events) {
    String json = JsonConverter.toJson(events);
    byte[] encodedBytes = null;
    try {/*from   ww  w.  j av  a2s  .  com*/
        ByteBuffer byteBuffer = UTF_ENCODER.encode(CharBuffer.wrap(json));
        encodedBytes = byteBuffer.array();
    } catch (CharacterCodingException e) {
        LOGGER.warn("Could not encode message with UTF-8.");
        encodedBytes = json.getBytes();
    }
    return new String(Base64.encode(zip(encodedBytes)));
}

From source file:Main.java

public static final boolean isPredessorEquals(final ByteBuffer bb1, final int offset1, final int l1,
        final ByteBuffer bb2, final int offset2, final int l2) {
    // return v1.compareToIgnoreCase(v2) <= 0;
    if (l1 <= 0) {
        return false;
    } else if (l2 <= 0) {
        return true;
    }/*  w  w w  .  j a v a2s  . c  o m*/
    return compareTo(bb1.array(), offset1, l1, bb2.array(), offset2, l2) <= 0;
}

From source file:io.alicorn.server.http.LoginEndpoint.java

public static String hash(char[] chars) {
    //Parse chars into bytes for hashing.
    CharBuffer charBuffer = CharBuffer.wrap(chars);
    ByteBuffer byteBuffer = charset.encode(charBuffer);
    byte[] bytes = Arrays.copyOfRange(byteBuffer.array(), byteBuffer.position(), byteBuffer.limit());

    //Clear temporary arrays of any data.
    Arrays.fill(charBuffer.array(), '\u0000');
    Arrays.fill(byteBuffer.array(), (byte) 0);

    //Generate the SHA-256 hash.
    String hash = hash(bytes);/*from w w w .  j  a  va2s .com*/

    //Clear remaining arrays of any data.
    Arrays.fill(bytes, (byte) 0);

    return hash;
}

From source file:gobblin.util.io.StreamUtils.java

/**
 * Reads the full contents of a ByteBuffer and writes them to an OutputStream. The ByteBuffer is
 * consumed by this operation; eg in.remaining() will be 0 after it completes successfully.
 * @param in  ByteBuffer to write into the OutputStream
 * @param out Destination stream/*from  w ww .  j  a  v  a 2 s.c om*/
 * @throws IOException If there is an error writing into the OutputStream
 */
public static void byteBufferToOutputStream(ByteBuffer in, OutputStream out) throws IOException {
    final int BUF_SIZE = 8192;

    if (in.hasArray()) {
        out.write(in.array(), in.arrayOffset() + in.position(), in.remaining());
    } else {
        final byte[] b = new byte[Math.min(in.remaining(), BUF_SIZE)];
        while (in.remaining() > 0) {
            int bytesToRead = Math.min(in.remaining(), BUF_SIZE);
            in.get(b, 0, bytesToRead);

            out.write(b, 0, bytesToRead);
        }
    }
}

From source file:biz.karms.sinkit.ejb.util.CIDRUtils.java

public static ImmutablePair<String, String> getStartEndAddresses(final String cidr)
        throws UnknownHostException {
    //TODO: This is silly. Refactor CIDRUtils so as to accept actual IPs as well as subnets.
    //TODO: Validate the thing before processing. Guava?
    final String fixedCIDR;
    if (!cidr.contains("/")) {
        //IPv6? Hmmm...
        if (cidr.contains(":")) {
            fixedCIDR = cidr + "/128";
        } else {//  www  . j  a  v a 2  s  .c  o  m
            fixedCIDR = cidr + "/32";
        }
    } else {
        fixedCIDR = cidr;
    }
    final int index = fixedCIDR.indexOf("/");
    final InetAddress inetAddress = InetAddress.getByName(fixedCIDR.substring(0, index));
    final int prefixLength = Integer.parseInt(fixedCIDR.substring(index + 1));

    final ByteBuffer maskBuffer;
    if (inetAddress.getAddress().length == 4) {
        maskBuffer = ByteBuffer.allocate(4).putInt(-1);
    } else {
        maskBuffer = ByteBuffer.allocate(16).putLong(-1L).putLong(-1L);
    }

    final BigInteger mask = (new BigInteger(1, maskBuffer.array())).not().shiftRight(prefixLength);
    final ByteBuffer buffer = ByteBuffer.wrap(inetAddress.getAddress());
    final BigInteger ipVal = new BigInteger(1, buffer.array());
    final BigInteger startIp = ipVal.and(mask);
    final BigInteger endIp = startIp.add(mask.not());

    return new ImmutablePair<>(String.format("%040d", startIp), String.format("%040d", endIp));
}

From source file:com.amazonaws.services.sqs.MessageMD5ChecksumHandler.java

/**
 * Update the digest using a sequence of bytes that consists of the length
 * (in 4 bytes) of the input ByteBuffer and all the bytes it contains.
 *///from w w  w.  java 2  s.c  o m
private static void updateLengthAndBytes(MessageDigest digest, ByteBuffer binaryValue) {
    // Rewind the ByteBuffer, in case that get/put operations were applied to
    // the unmarshalled BB before it's passed to this handler.
    binaryValue.rewind();
    int size = binaryValue.remaining();
    ByteBuffer lengthBytes = ByteBuffer.allocate(INTEGER_SIZE_IN_BYTES).putInt(size);
    digest.update(lengthBytes.array());
    digest.update(binaryValue);
}

From source file:android.wulongdao.thirdparty.mime.HttpMultipart.java

private static ByteArrayBuffer encode(final Charset charset, final String string) {
    ByteBuffer encoded = charset.encode(CharBuffer.wrap(string));
    ByteArrayBuffer bab = new ByteArrayBuffer(encoded.remaining());
    bab.append(encoded.array(), encoded.position(), encoded.remaining());
    return bab;/*  ww  w  .  j  a va  2  s  .c o m*/
}