Example usage for org.bouncycastle.crypto BufferedBlockCipher getBlockSize

List of usage examples for org.bouncycastle.crypto BufferedBlockCipher getBlockSize

Introduction

In this page you can find the example usage for org.bouncycastle.crypto BufferedBlockCipher getBlockSize.

Prototype

public int getBlockSize() 

Source Link

Document

return the blocksize for the underlying cipher.

Usage

From source file:com.github.horrorho.inflatabledonkey.pcs.xfile.BlockDecrypters.java

License:Open Source License

static BlockDecrypter create(BufferedBlockCipher cipher, Digest digest, byte[] key) {
    ParametersWithIV blockIVKey = blockIVKey(digest, cipher.getBlockSize(), key);
    KeyParameter keyParameter = new KeyParameter(key);

    return new BlockDecrypter(cipher, blockIVKey, keyParameter);
}

From source file:com.gpfcomics.android.cryptnos.ImportExportHandler.java

License:Open Source License

/**
 * Given a cipher and the size of an input file, determine whether or not we have
 * enough memory on hand to encrypt or decrypt the data.  Since we have to do all
 * our cryptography in memory, we can only work with the amount of memory
 * currently available.//from   w w  w.jav a  2 s .  c  o  m
 * @param cipher The BufferedBlockCipher we'll be using to encrypt/decrypt
 * @param fileSize The size of the input file in bytes
 * @param caller The calling activity
 * @return True if there's sufficient memory to decrypt the file, false otherwise
 */
private static boolean haveSufficientMemory(BufferedBlockCipher cipher, boolean encrypting, long fileSize,
        Activity caller) {
    // There are other factors that should eliminate this before we get to this
    // step, but we can't deal with a file larger than 2GB.  There aren't any
    // current Android devices with that much RAM anyway.
    if (fileSize > (long) Integer.MAX_VALUE)
        return false;
    // As an error check, make sure the cipher and caller objects are not null:
    if (cipher == null || caller == null)
        return false;
    // Now put on our asbestos underpants:
    try {
        // Get the memory information from the activity service:
        MemoryInfo mi = new MemoryInfo();
        ActivityManager activityManager = (ActivityManager) caller.getSystemService(Context.ACTIVITY_SERVICE);
        activityManager.getMemoryInfo(mi);
        // In order to decrypt the file, we'll need at least as many bytes as
        // the encrypted and decrypted data combined.  In order to get this,
        // we'll add the size of the input file to the output size of the data
        // after it passes through the cipher.  Note that it doesn't matter
        // whether we're doing encryption or decryption at this point; the cipher
        // object knows and the output size will be appropriate for the output
        // mode.  If the sum of these two values is less than the available
        // memory, we should be good to go.
        //return mi.availMem > fileSize + (long)cipher.getOutputSize((int)fileSize);
        if (encrypting)
            return mi.availMem > fileSize + (long) cipher.getOutputSize((int) fileSize);
        else
            return mi.availMem > (long) cipher.getBlockSize() + (long) cipher.getOutputSize((int) fileSize);
    } catch (Exception e) {
        return false;
    }
}

From source file:fc.xml.xas.security.DecryptSource.java

License:Open Source License

private void decryptAndParseBytes(byte[] data, byte[] key, BufferedBlockCipher cipher, StartTag context,
        String mimeType, boolean isGzip) throws IOException {
    if (Log.isEnabled(Log.DEBUG)) {
        Log.debug("Decrypting bytes", Util.toPrintable(data));
    }/*from   www .  java2s . co m*/
    Object token = Measurer.get(Measurer.TIMING).start();
    byte[] iv = new byte[cipher.getBlockSize()];
    System.arraycopy(data, 0, iv, 0, iv.length);
    cipher.init(false, new ParametersWithIV(new KeyParameter(key), iv));
    int size = cipher.getOutputSize(data.length - iv.length);
    byte[] result = new byte[size];
    int off = cipher.processBytes(data, iv.length, data.length - iv.length, result, 0);
    try {
        off += cipher.doFinal(result, off);
    } catch (InvalidCipherTextException ex) {
        ex.printStackTrace();
        throw new IOException(ex.getMessage());
    }
    Measurer.get(Measurer.TIMING).finish(token, "Symmetric decryption time");
    if (Log.isEnabled(Log.DEBUG)) {
        Log.debug("Decrypted bytes", Util.toPrintable(result, 0, off));
    }
    FormatFactory factory = XasUtil.getFactory(mimeType);
    if (factory == null) {
        throw new IOException("MIME type " + mimeType + " not recognized");
    }
    token = Measurer.get(Measurer.TIMING).start();
    ByteArrayInputStream bin = new ByteArrayInputStream(result, 0, off);
    InputStream in = isGzip ? new GZIPInputStream(bin) : bin;
    ItemSource itemSource = TypingUtil.typedSource(factory.createSource(in), mimeType, "UTF-8");
    XasUtil.copyFragment(itemSource, storage);
    Measurer.get(Measurer.TIMING).finish(token, "Parsing decrypted data");
}

From source file:net.sourceforge.keepassj2me.keydb.KeydbDatabase.java

License:Open Source License

/**
 * Encode database/*  ww w  .  ja va2s  . c o m*/
 * @return encoded database
 * @throws KeydbException
 */
public byte[] getEncoded() throws KeydbException {//Encrypt content
    if (isLocked())
        return this.encodedContent;

    if ((this.header.numGroups == 0) && (this.header.numEntries == 0))
        throw new KeydbException(Config.getLocaleString(keys.KD_NOTHING_SAVE));

    BufferedBlockCipher cipher = new BufferedBlockCipher(new CBCBlockCipher(new AESEngine()));

    //calc padding size
    int block_size = cipher.getBlockSize();
    int pad_size = block_size - this.contentSize % block_size;

    // #ifdef DEBUG
    System.out.println("contentSize: " + this.contentSize);
    System.out.println("block_size: " + block_size);
    System.out.println("pad_size: " + pad_size);
    // #endif

    //add padding to content
    byte temp[] = new byte[this.contentSize + pad_size];
    System.arraycopy(this.plainContent, 0, temp, 0, this.contentSize);
    KeydbUtil.fill(this.plainContent, (byte) 0);
    this.plainContent = temp;
    temp = null;
    PKCS7Padding padding = new PKCS7Padding();
    padding.addPadding(this.plainContent, this.contentSize);

    byte encoded[] = new byte[KeydbHeader.SIZE + this.contentSize + pad_size];

    //encode
    cipher.init(true, new ParametersWithIV(new KeyParameter(this.key), this.header.encryptionIV));

    int paddedEncryptedPartSize = cipher.processBytes(this.plainContent, 0, this.plainContent.length, encoded,
            KeydbHeader.SIZE);

    if (paddedEncryptedPartSize != this.plainContent.length) {
        // #ifdef DEBUG
        System.out.println("Encoding: " + paddedEncryptedPartSize + " != " + this.plainContent.length);
        // #endif
        throw new KeydbException(Config.getLocaleString(keys.KD_ENCRYPTING_FAILED));
    }

    //Set header
    this.header.contentsHash = KeydbUtil.hash(this.plainContent, 0, this.contentSize);
    this.header.write(encoded, 0);

    return encoded;
}

From source file:org.opcfoundation.ua.transport.tcp.impl.ChunkSymmEncryptSigner.java

License:Open Source License

private int symmetricEncrypt(SecurityToken token, byte[] dataToEncrypt, int inputOffset, int inputLength,
        byte[] output, int outputOffset) throws ServiceResultException {

    //Make RijndaelEngine for encryption
    RijndaelEngine engine = new RijndaelEngine(token.getEncryptionBlockSize() * 8);
    //check right instance for cipher

    try {//from   www  .j  a v a 2s .com
        //TODO should we check that mode is CBC?
        //blockCipher CBC
        BufferedBlockCipher cipher = new BufferedBlockCipher(new CBCBlockCipher(engine));

        cipher.init(true, new ParametersWithIV(new KeyParameter(token.getLocalEncryptingKey()),
                token.getLocalInitializationVector()));

        //Check that input data is even with the encryption blocks
        if (dataToEncrypt.length % cipher.getBlockSize() != 0) {
            //ERROR
            LOGGER.error("Input data is not an even number of encryption blocks.");
            //throw new ServiceResultException(StatusCodes.Bad_InternalError,"Error in symmetric decrypt: Input data is not an even number of encryption blocks.");
        }

        int crypted = cipher.processBytes(dataToEncrypt, inputOffset, inputLength, output, outputOffset);
        //log.error("ChunkSymmEncrypter/encrypt: Processed bytes: "+crypted);
        crypted += cipher.doFinal(output, outputOffset + crypted);

        return crypted;
    } //TODO remoce print  traces
    catch (DataLengthException e) {
        e.printStackTrace();
    } catch (IllegalStateException e) {
        e.printStackTrace();
    } catch (InvalidCipherTextException e) {
        e.printStackTrace();
    }
    LOGGER.error("EXCEPTION from symmetric exception!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!");

    throw new ServiceResultException(StatusCodes.Bad_InternalError, "Error in symmetric encrypt");
}

From source file:org.sperle.keepass.crypto.bc.AESCipher.java

License:Open Source License

public byte[] encrypt(byte[] key, byte[] plainText, byte[] iv, int rounds, boolean padding, ProgressMonitor pm)
        throws KeePassCryptoException {
    try {//  w  w  w .j ava  2s . com
        BufferedBlockCipher cipher = null;
        if (padding) {
            cipher = new PaddedBufferedBlockCipher(new CBCBlockCipher(new AESEngine()));
        } else {
            cipher = new BufferedBlockCipher(new AESEngine());
        }

        if (iv != null)
            cipher.init(true, new ParametersWithIV(new KeyParameter(key), iv));
        else
            cipher.init(true, new KeyParameter(key));

        if (pm != null) {
            if (rounds == 1)
                pm.nextStep(plainText.length / cipher.getBlockSize(), "pm_encrypt"); // count length (database)
            else if (rounds > 1)
                pm.nextStep(rounds, "pm_encrypt"); // count rounds (master password)
        }

        byte[] cipherText = null;
        if (padding) {
            cipherText = new byte[cipher.getOutputSize(plainText.length)];
        } else {
            cipherText = new byte[plainText.length];
        }

        int outLength = cipher.processBytes(plainText, 0, plainText.length, cipherText, 0,
                rounds == 1 ? pm : null);
        if (outLength == -1)
            return null; // user canceled
        if (rounds > 1) {
            if (pm != null)
                pm.tick();
            for (int i = 1; i < rounds; i++) {
                outLength = cipher.processBytes(cipherText, 0, cipherText.length, cipherText, 0, null);
                if (pm != null) {
                    if (pm.isCanceled())
                        return null;
                    pm.tick();
                }
            }
        }

        if (padding)
            cipher.doFinal(cipherText, outLength);
        return cipherText;
    } catch (Exception e) {
        throw new KeePassCryptoException("Exception during AES encryption: " + e.getMessage());
    }
}

From source file:org.sperle.keepass.crypto.bc.AESCipher.java

License:Open Source License

public byte[] decrypt(byte[] key, byte[] cipherText, byte[] iv, ProgressMonitor pm)
        throws KeePassCryptoException {
    try {//ww  w.j  a  v a2 s  . c  om
        BufferedBlockCipher cipher = new PaddedBufferedBlockCipher(new CBCBlockCipher(new AESEngine()));
        if (iv != null)
            cipher.init(false, new ParametersWithIV(new KeyParameter(key), iv));
        else
            cipher.init(false, new KeyParameter(key));
        if (pm != null)
            pm.nextStep(cipherText.length / cipher.getBlockSize(), "pm_decrypt");
        byte[] plainText = new byte[cipher.getOutputSize(cipherText.length)];
        int outLength = cipher.processBytes(cipherText, 0, cipherText.length, plainText, 0, pm);
        if (outLength == -1)
            return null; // user canceled
        outLength += cipher.doFinal(plainText, outLength);
        return (outLength < plainText.length) ? ByteArrays.cut(plainText, outLength) : plainText;
    } catch (Exception e) {
        throw new KeePassCryptoException("Exception during AES decryption: " + e.getMessage());
    }
}

From source file:piecework.security.concrete.ExampleBouncyCastleEncryptionService.java

License:Educational Community License

@Override
public Secret encrypt(String text)
        throws InvalidCipherTextException, UnsupportedEncodingException, GeneralSecurityException {
    BufferedBlockCipher cipher = cipher();

    SecretKeyRing secretKeyRing = keyProvider.getEncryptionKeyRing(null, null);

    byte[] key = secretKeyRing.getSecretKey().getEncoded();
    byte[] iv = new byte[cipher.getBlockSize()];

    // Generate a random initialization vector for this encryption
    random.nextBytes(iv);/*from  ww w  . j ava  2  s .  c  om*/

    cipher.init(true, new ParametersWithIV(new KeyParameter(key), iv));

    byte[] clear = text.getBytes("UTF-8");
    int outputSize = cipher.getOutputSize(clear.length);
    byte[] hidden = new byte[outputSize];
    int bytesProcessed = cipher.processBytes(clear, 0, clear.length, hidden, 0);
    bytesProcessed += cipher.doFinal(hidden, bytesProcessed);

    if (bytesProcessed != hidden.length)
        throw new GeneralSecurityException("Unable to correctly encrypt input data");

    return new Secret.Builder().id(uuidGenerator.getNextId()).name(secretKeyRing.getKeyName()).date(new Date())
            .ciphertext(Base64.encode(hidden)).iv(Base64.encode(iv)).build();
}