Example usage for javax.crypto Cipher getOutputSize

List of usage examples for javax.crypto Cipher getOutputSize

Introduction

In this page you can find the example usage for javax.crypto Cipher getOutputSize.

Prototype

public final int getOutputSize(int inputLen) 

Source Link

Document

Returns the length in bytes that an output buffer would need to be in order to hold the result of the next update or doFinal operation, given the input length inputLen (in bytes).

Usage

From source file:org.hardisonbrewing.s3j.FileSyncer.java

public PutObjectResult put(File file, boolean encrypted) throws Exception {

    if (!encrypted || privateKey == null) {
        return put(file);
    }//from   www  .j  a  v a 2  s  . co  m

    long decryptedLength = file.length();
    String path = getBucketPath(file);

    byte[] rawKey = AesUtil.generateKey();
    Cipher cipher = Cipher.getInstance(AesUtil.ALGORITHM);
    cipher.init(Cipher.ENCRYPT_MODE, new SecretKeySpec(rawKey, AesUtil.ALGORITHM));

    int encryptedLength = cipher.getOutputSize((int) file.length());

    InputStream inputStream = null;

    try {
        inputStream = new FileInputStream(file);
        inputStream = new CipherInputStream(inputStream, cipher);
        put(path, inputStream, encryptedLength);
    } finally {
        IOUtil.close(inputStream);
    }

    byte[] encryptedKey = RsaUtil.encrypt(privateKey, rawKey);

    DataProperties properties = new DataProperties();
    properties.put(PROP_ALGORITHM, AesUtil.ALGORITHM);
    properties.put(PROP_DECRYPTED_LENGTH, decryptedLength);
    properties.put(PROP_ENCRYPTED_LENGTH, encryptedLength);
    properties.put(PROP_KEY, encryptedKey);
    properties.put(PROP_ORIG_FILE_PATH, file.getAbsolutePath());
    properties.put(PROP_LAST_MODIFIED, file.lastModified());
    uploadProperties(path, properties);

    PutObjectResult response = new PutObjectResult();
    response.file = file;
    response.properties = properties;
    response.bucketPath = path;
    return response;
}

From source file:com.zacwolf.commons.crypto._CRYPTOfactory.java

public final byte[] encrypt(final byte[] bytes)
        throws InvalidKeyException, IllegalBlockSizeException, BadPaddingException, NoSuchAlgorithmException,
        NoSuchPaddingException, InvalidAlgorithmParameterException {
    ready();/* w w  w.  j  a  v a 2 s. c  om*/
    activecrypts++;
    try {
        final Cipher ecipher = this.crypter.getEcipher();
        byte[] salt = ecipher.getIV();
        final ByteBuffer outbuf = ByteBuffer
                .allocate(ecipher.getOutputSize(bytes.length) + (salt != null ? salt.length : 0) + 1);
        if (salt != null) {
            outbuf.put((byte) salt.length);
            outbuf.put(salt);
        } else
            outbuf.put((byte) 0);
        try {
            ecipher.doFinal(ByteBuffer.wrap(bytes), outbuf);
        } catch (ShortBufferException e) {
            // not going to happen since we specifically allocate based on the cipher output size
        }
        return outbuf.array();
    } finally {
        activecrypts--;
    }
}

From source file:org.jets3t.service.security.EncryptionUtil.java

/**
 * Returns an estimate of the number of bytes that will result when data
 * of the given length is encrypted. The accuracy of this estimate may
 * depend on the cipher you are using, so be wary of trusting this estimate
 * without supporting evidence.//from   ww w. ja va  2 s. co m
 *
 * @param inputSize
 * The number of bytes you intend to encrypt.
 *
 * @return
 * an estimate of the number of bytes that will be generated by the
 * encryption cipher for the given number of bytes of input.
 *
 * @throws InvalidKeyException
 * @throws InvalidAlgorithmParameterException
 * @throws NoSuchAlgorithmException
 * @throws NoSuchPaddingException
 */
public long getEncryptedOutputSize(long inputSize) throws InvalidKeyException,
        InvalidAlgorithmParameterException, NoSuchAlgorithmException, NoSuchPaddingException {
    Cipher cipher = initEncryptModeCipher();
    long outputSize = 0;

    // Break input size into integer-sized chunks so we can estimate values
    // for large inputs.
    int maxChunk = Integer.MAX_VALUE - 8192;
    while (inputSize >= maxChunk) {
        outputSize += cipher.getOutputSize(maxChunk);
        inputSize -= maxChunk;
    }
    outputSize += cipher.getOutputSize((int) inputSize);
    return outputSize;
}

From source file:org.signserver.server.cryptotokens.PKCS11CryptoToken.java

private byte[] cryptDataBytes(Cipher cipher, byte[] dataBytes, boolean encription)
        throws BadPaddingException, IllegalBlockSizeException, IOException {
    int blockSize = cipher.getBlockSize();
    int outputSize = cipher.getOutputSize(blockSize);
    if (blockSize == 0) {
        blockSize = outputSize - 11;//from   ww  w .j  a  va 2s. c  om
    }

    int readingBlockSize = 0;
    if (encription) {
        readingBlockSize = blockSize;
    } else {
        readingBlockSize = outputSize;
    }

    int inLen = dataBytes.length;
    int fullBlockCount = inLen / readingBlockSize;

    ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
    int inOffset = 0;
    for (int i = 0; i < fullBlockCount; i++) {
        outputStream.write(cipher.doFinal(dataBytes, inOffset, readingBlockSize));
        inOffset += readingBlockSize;
    }
    if (inOffset < inLen) {
        outputStream.write(cipher.doFinal(dataBytes, inOffset, inLen - inOffset));
    }
    return outputStream.toByteArray();
}

From source file:org.usergrid.persistence.Schema.java

public static ByteBuffer encrypt(ByteBuffer clear) {
    if (clear == null || !clear.hasRemaining())
        return clear;
    try {//w ww .  j  a  va2s  .  c o m
        SecretKeySpec sKeySpec = new SecretKeySpec(getRawKey(encryptionSeed), "AES");
        Cipher cipher = Cipher.getInstance("AES");
        cipher.init(Cipher.ENCRYPT_MODE, sKeySpec);
        ByteBuffer encrypted = ByteBuffer.allocate(cipher.getOutputSize(clear.remaining()));
        cipher.doFinal(clear, encrypted);
        encrypted.rewind();
        return encrypted;
    } catch (Exception e) {
        throw new IllegalStateException(e);
    }
}

From source file:org.usergrid.persistence.Schema.java

public static ByteBuffer decrypt(ByteBuffer encrypted) {
    if (encrypted == null || !encrypted.hasRemaining())
        return encrypted;
    try {/*  ww w.j  a  va 2 s  .  c om*/
        SecretKeySpec sKeySpec = new SecretKeySpec(getRawKey(encryptionSeed), "AES");
        Cipher cipher = Cipher.getInstance("AES");
        cipher.init(Cipher.DECRYPT_MODE, sKeySpec);
        ByteBuffer decrypted = ByteBuffer.allocate(cipher.getOutputSize(encrypted.remaining()));
        cipher.doFinal(encrypted, decrypted);
        decrypted.rewind();
        return decrypted;
    } catch (Exception e) {
        throw new IllegalStateException(e);
    }
}

From source file:acp.sdk.SecureUtil.java

/**
 * /*www.  java2 s.c o m*/
 * @param publicKey
 * @param plainData
 * @return
 * @throws Exception
 */
public byte[] encryptedData(PublicKey publicKey, byte[] plainData) throws Exception {
    try {
        //         Cipher cipher = CliperInstance.getInstance();
        Cipher cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding", "BC");
        cipher.init(Cipher.ENCRYPT_MODE, publicKey);
        int blockSize = cipher.getBlockSize();
        int outputSize = cipher.getOutputSize(plainData.length);
        int leavedSize = plainData.length % blockSize;
        int blocksSize = leavedSize != 0 ? plainData.length / blockSize + 1 : plainData.length / blockSize;
        byte[] raw = new byte[outputSize * blocksSize];
        int i = 0;
        while (plainData.length - i * blockSize > 0) {
            if (plainData.length - i * blockSize > blockSize) {
                cipher.doFinal(plainData, i * blockSize, blockSize, raw, i * outputSize);
            } else {
                cipher.doFinal(plainData, i * blockSize, plainData.length - i * blockSize, raw, i * outputSize);
            }
            i++;
        }
        return raw;
    } catch (Exception e) {
        throw new Exception(e.getMessage());
    }
}

From source file:cn.usually.common.pay.union.sdk.SecureUtil.java

/**
 * /*from w w  w . j  a  v  a  2  s  .  c  om*/
 * @param publicKey
 * @param plainData
 * @return
 * @throws Exception
 */
public byte[] encryptedData(PublicKey publicKey, byte[] plainData) throws Exception {
    try {
        Cipher cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding",
                new org.bouncycastle.jce.provider.BouncyCastleProvider());
        cipher.init(Cipher.ENCRYPT_MODE, publicKey);
        int blockSize = cipher.getBlockSize();
        int outputSize = cipher.getOutputSize(plainData.length);
        int leavedSize = plainData.length % blockSize;
        int blocksSize = leavedSize != 0 ? plainData.length / blockSize + 1 : plainData.length / blockSize;
        byte[] raw = new byte[outputSize * blocksSize];
        int i = 0;
        while (plainData.length - i * blockSize > 0) {
            if (plainData.length - i * blockSize > blockSize) {
                cipher.doFinal(plainData, i * blockSize, blockSize, raw, i * outputSize);
            } else {
                cipher.doFinal(plainData, i * blockSize, plainData.length - i * blockSize, raw, i * outputSize);
            }
            i++;
        }
        return raw;
    } catch (Exception e) {
        throw new Exception(e.getMessage());
    }
}

From source file:com.charabia.SmsViewActivity.java

@Override
public void onActivityResult(int reqCode, int resultCode, Intent data) {
    super.onActivityResult(reqCode, resultCode, data);

    switch (reqCode) {
    case SMS_KEY_CONTACT:
        if (resultCode == RESULT_OK) {
            Uri uri = data.getData();/*from ww  w . j a  v  a 2s.  com*/

            ContentResolver cr = getContentResolver();

            Cursor cursor = cr.query(uri, new String[] { Contacts.LOOKUP_KEY }, null, null, null);

            String lookup = null;

            if (cursor.moveToFirst()) {
                lookup = cursor.getString(0);
            }

            cursor.close();

            if (lookup == null) {
                Toast.makeText(this, R.string.unexpected_error, Toast.LENGTH_LONG).show();
                return;
            }

            cursor = cr.query(Data.CONTENT_URI, new String[] { Phone.NUMBER },
                    Data.MIMETYPE + "=? AND " + Data.LOOKUP_KEY + "=?",
                    new String[] { Phone.CONTENT_ITEM_TYPE, lookup }, null);

            ArrayList<String> options = new ArrayList<String>();

            while (cursor.moveToNext()) {
                options.add(cursor.getString(0));
            }

            cursor.close();

            final String[] phoneList = options.toArray(new String[0]);

            Builder builder = new AlertDialog.Builder(this);
            builder.setTitle(R.string.send_invit_on_phone);
            builder.setItems(phoneList, new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialogInterface, int i) {

                    keypair = tools.loadKeyPair();
                    RSAPublicKey pubKey = (RSAPublicKey) keypair.getPublic();

                    byte[] encoded = pubKey.getModulus().toByteArray();

                    byte[] data = new byte[3 + encoded.length];

                    data[0] = Tools.MAGIC[0];
                    data[1] = Tools.MAGIC[1];
                    data[2] = Tools.PUBLIC_KEY_TYPE;

                    System.arraycopy(encoded, 0, data, 3, encoded.length);

                    tools.sendData(phoneList[i], Tools.INVITATION, "", data);

                }
            });

            builder.create().show();
        } else {
            Toast.makeText(this, R.string.error_create_key, Toast.LENGTH_LONG).show();
        }
        break;
    case IntentIntegrator.REQUEST_CODE:
        if (resultCode == RESULT_OK) {
            try {
                String contents = data.getStringExtra("SCAN_RESULT");
                @SuppressWarnings("unused")
                String format = data.getStringExtra("SCAN_RESULT_FORMAT");
                // Handle successful scan

                // TODO: add more tests control

                String[] infos = contents.split("\n");

                Cipher rsaCipher = Cipher.getInstance(Tools.RSA_CIPHER_ALGO);

                if (mode == MODE_ESCLAVE) {
                    // Save key and show crypted key on QRCode
                    key = tools.generateKeyAES().getEncoded();

                    KeyFactory keyFact = KeyFactory.getInstance("RSA");

                    PublicKey pubkey = keyFact.generatePublic(
                            new RSAPublicKeySpec(new BigInteger(infos[1]), new BigInteger(infos[2])));

                    rsaCipher.init(Cipher.ENCRYPT_MODE, pubkey);

                    int blockSize = rsaCipher.getBlockSize();

                    int nbBlock = key.length / blockSize;
                    int reste = key.length % blockSize;

                    byte[] cryptedKey = new byte[(nbBlock + 1) * rsaCipher.getOutputSize(blockSize)];

                    int offset = 0;

                    for (int i = 0; i < nbBlock; i++) {
                        offset += rsaCipher.doFinal(key, i * blockSize, blockSize, cryptedKey, offset);
                    }

                    rsaCipher.doFinal(key, nbBlock * blockSize, reste, cryptedKey, offset);

                    IntentIntegrator.shareText(SmsViewActivity.this,
                            prefPhoneNumber + "\n" + Base64.encodeToString(cryptedKey, Base64.NO_WRAP));

                } else {

                    // We have read crypted key, so decode it
                    rsaCipher.init(Cipher.DECRYPT_MODE, keypair.getPrivate());

                    byte[] cryptedData = Base64.decode(infos[1], Base64.NO_WRAP);

                    int blockSize = rsaCipher.getBlockSize();
                    int nbBlock = cryptedData.length / blockSize;

                    int offset = 0;

                    byte[] tempKey = new byte[(nbBlock + 1) * blockSize];

                    for (int i = 0; i < nbBlock; i++) {
                        offset += rsaCipher.doFinal(cryptedData, i * blockSize, blockSize, tempKey, offset);
                    }

                    key = new byte[offset];
                    System.arraycopy(tempKey, 0, key, 0, offset);
                }

                phoneNumber = infos[0];

                // store the key
                // TODO dialog to confirm add contact in mode SLAVE
                try {
                    new Tools(this).updateOrCreateContactKey(phoneNumber, key);
                } catch (NoContactException e) {
                    e.printStackTrace();
                    // propose to add contact
                    Intent newIntent = new Intent(Intents.SHOW_OR_CREATE_CONTACT);
                    newIntent.setData(Uri.fromParts("tel", phoneNumber, null));
                    startActivityForResult(newIntent, ADD_CONTACT);
                    return;
                }

                Toast.makeText(this, getString(R.string.contact_added) + "\n" + phoneNumber, Toast.LENGTH_LONG)
                        .show();

            } catch (Exception e) {
                e.printStackTrace();
                Toast.makeText(this, R.string.error_create_key, Toast.LENGTH_LONG).show();
            }

        } else {
            // TODO: string
            Toast.makeText(this, R.string.fail_reading_tag, Toast.LENGTH_LONG).show();
        }
        break;
    case ADD_CONTACT:
        try {
            tools.updateOrCreateContactKey(phoneNumber, key);
            Toast.makeText(this, getString(R.string.contact_added) + "\n" + phoneNumber, Toast.LENGTH_LONG)
                    .show();
        } catch (NoContactException e) {
            e.printStackTrace();
            Toast.makeText(this, R.string.error_create_key, Toast.LENGTH_LONG).show();
        }
        break;
    }

}

From source file:com.example.nfcreaderorigin.MainActivity.java

private byte[] Encrypter(byte[] input) throws Exception {

    // Security.addProvider(new MainActivity().BouncyCastleProvider());    

    byte[] keyBytes = new byte[] { 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d,
            0x0e, 0x0f, 0x10 };/*  w  ww .  j  a v a  2 s  . c  o  m*/

    SecretKeySpec key = new SecretKeySpec(keyBytes, "AES");

    Cipher cipher = Cipher.getInstance("AES/ECB/PKCS7Padding", "BC");

    //mTxtInput.setText(new String(data));
    //System.out.println(new String(input));

    // encryption pass
    cipher.init(Cipher.ENCRYPT_MODE, key);

    byte[] cipherText = new byte[cipher.getOutputSize(input.length)];
    int ctLength = cipher.update(input, 0, input.length, cipherText, 0);
    ctLength += cipher.doFinal(cipherText, ctLength);

    return cipherText;
    //System.out.println(new String(cipherText));
    //System.out.println(ctLength);

    // mTxtCipher.setText(new String(cipherText));
    // mTxtCtLenght.setText(String.valueOf(ctLength));
    // decryption pass

}