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

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

Introduction

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

Prototype

public AESEngine() 

Source Link

Document

default constructor - 128 bit block size.

Usage

From source file:org.ourfilesystem.security.SecurityTools.java

License:Open Source License

public static String decodePublicPost(BBytes enc, RSAPrivateCrtKeyParameters key) {
    try {//from   w  w w . j a  va  2 s  .  com
        byte encdata[] = enc.getBytes();

        //Extract the header
        ByteBuffer bbuf = ByteBuffer.wrap(encdata);
        int headlen = bbuf.getInt();
        if (headlen > 4096) {
            throw new Exception("Header is too long: " + headlen);
        }
        byte head[] = new byte[headlen];
        System.arraycopy(encdata, Integer.SIZE / Byte.SIZE, head, 0, headlen);

        //Decode the header
        RSAEngine eng = new RSAEngine();
        PKCS1Encoding eng2 = new PKCS1Encoding(eng);
        eng2.init(false, key);

        byte dechead[] = eng2.processBlock(head, 0, head.length);
        if (dechead.length < (2 * Long.SIZE / Byte.SIZE)) {
            //Magic number can't be there, not enough data.
            return null;
        }
        ByteBuffer mbuf = ByteBuffer.wrap(dechead);
        long m0 = mbuf.getLong();
        long m1 = mbuf.getLong();
        if (m0 != 0x01234567) {
            return null;
        }
        if (m1 != 0x76543210) {
            return null;
        }
        //Exctract the symmetric key.
        byte skey[] = new byte[dechead.length - (2 * Long.SIZE / Byte.SIZE)];
        System.arraycopy(dechead, 2 * Long.SIZE / Byte.SIZE, skey, 0, skey.length);

        KeyParameter kp = new KeyParameter(skey);

        CBCBlockCipher aes = new CBCBlockCipher(new AESEngine());
        PaddedBufferedBlockCipher cipher = new PaddedBufferedBlockCipher(aes, new PKCS7Padding());
        cipher.init(false, kp);

        int foffset = (Integer.SIZE / Byte.SIZE) + headlen;
        int enclen = encdata.length - foffset;
        byte[] output = new byte[cipher.getOutputSize(enclen)];
        int len = cipher.processBytes(encdata, foffset, enclen, output, 0);
        int len2 = cipher.doFinal(output, len);

        byte rawdata[] = new byte[len + len2];

        System.arraycopy(output, 0, rawdata, 0, rawdata.length);

        return new String(rawdata, Charset.forName("UTF-16BE"));
    } catch (Exception e) {
        //e.printStackTrace();         
    }
    return null;
}

From source file:org.ourfilesystem.security.SecurityTools.java

License:Open Source License

public static BBytes encodePublicPost(String raw, PublicKeySet pubkey) {
    try {/*w  w  w. ja v a  2s  .  c  o m*/
        byte strb[] = raw.getBytes(Charset.forName("UTF-16BE"));

        byte[] key = new byte[32];
        Random.nextBytes(key);
        KeyParameter kp = new KeyParameter(key);

        CBCBlockCipher aes = new CBCBlockCipher(new AESEngine());
        PaddedBufferedBlockCipher cipher = new PaddedBufferedBlockCipher(aes, new PKCS7Padding());
        cipher.init(true, kp);

        byte[] output = new byte[cipher.getOutputSize(strb.length)];
        int len = cipher.processBytes(strb, 0, strb.length, output, 0);
        cipher.doFinal(output, len);

        RSAEngine eng = new RSAEngine();

        byte headblk[] = new byte[(2 * Long.SIZE / Byte.SIZE) + key.length];
        ByteBuffer bbuf = ByteBuffer.wrap(headblk);
        bbuf.putLong(0x01234567); //magic number
        bbuf.putLong(0x76543210); //magic number
        System.arraycopy(key, 0, headblk, (2 * Long.SIZE / Byte.SIZE), key.length);

        PKCS1Encoding enc = new PKCS1Encoding(eng);
        enc.init(true, (CipherParameters) pubkey.getPublicEncryptionKey());

        byte enchead[] = enc.processBlock(headblk, 0, headblk.length);

        byte rslt[] = new byte[(Integer.SIZE / Byte.SIZE) + enchead.length + output.length];

        ByteBuffer rbuf = ByteBuffer.wrap(rslt);
        rbuf.putInt(enchead.length);
        System.arraycopy(enchead, 0, rslt, Integer.SIZE / Byte.SIZE, enchead.length);
        System.arraycopy(output, 0, rslt, (Integer.SIZE / Byte.SIZE) + enchead.length, output.length);

        BBytes orslt = new BBytes(rslt);
        return orslt;

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

    return null;
}

From source file:org.picketlink.json.jose.crypto.AES.java

License:Open Source License

/**
 * Creates a new AES cipher.//from  w w w .  j  a  v  a2 s. c om
 *
 * @param secretKey The AES key. Must not be {@code null}.
 * @param forEncryption If {@code true} creates an AES encryption cipher, else creates an AES decryption cipher.
 *
 * @return The AES cipher.
 */
public static AESEngine createCipher(final SecretKey secretKey, final boolean forEncryption) {

    AESEngine cipher = new AESEngine();
    CipherParameters cipherParams = new KeyParameter(secretKey.getEncoded());
    cipher.init(forEncryption, cipherParams);
    return cipher;
}

From source file:org.sandrob.KeyStoreUtils.ExportImport.java

License:Apache License

private static byte[] process(byte[] input, String password, boolean forEncryption) throws Exception {
    try {//from  www .j  av a  2 s  . c o m
        // generate key with iteration from password, salt
        SecretKeyFactory f = SecretKeyFactory.getInstance(KeyFactoryType, CryptoProvider);
        KeySpec ks = new PBEKeySpec(password.toCharArray(), getSaltByteArray(), KeyGenIterations, KeyLength);
        SecretKey s = f.generateSecret(ks);
        Key k = new SecretKeySpec(s.getEncoded(), KeyAlgorithm);
        CipherParameters cipherParameters = new KeyParameter(k.getEncoded());
        BlockCipher blockCipher = new AESEngine();
        BlockCipherPadding blockCipherPadding = new PKCS7Padding();
        BufferedBlockCipher bufferedBlockCipher = new PaddedBufferedBlockCipher(blockCipher,
                blockCipherPadding);

        // initialize the chiper
        bufferedBlockCipher.init(forEncryption, cipherParameters);

        int inputOffset = 0;
        int inputLength = input.length;

        int maximumOutputLength = bufferedBlockCipher.getOutputSize(inputLength);
        byte[] output = new byte[maximumOutputLength];
        int outputOffset = 0;
        int outputLength = 0;

        int bytesProcessed;

        // process input buffer
        bytesProcessed = bufferedBlockCipher.processBytes(input, inputOffset, inputLength, output,
                outputOffset);
        outputOffset += bytesProcessed;
        outputLength += bytesProcessed;

        // process the last block
        bytesProcessed = bufferedBlockCipher.doFinal(output, outputOffset);
        outputOffset += bytesProcessed;
        outputLength += bytesProcessed;

        if (outputLength == output.length) {
            return output;
        } else {
            byte[] truncatedOutput = new byte[outputLength];
            System.arraycopy(output, 0, truncatedOutput, 0, outputLength);
            return truncatedOutput;
        }
    } catch (Exception ex) {
        Log.e(TAG, ex.getMessage());
        throw new Exception(ex);
    }
}

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 ww . j a  v  a 2  s  .c o  m
        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 {/*from   w  w  w. ja v a  2 s . c o m*/
        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:org.spout.api.security.SecurityHandler.java

License:Open Source License

public BufferedBlockCipher getSymmetricCipher(String cipher, String wrapper) {
    if (cipher.equals("AES")) {
        return addSymmetricWrapper(new AESEngine(), wrapper);
    }//from w ww.  ja va  2s.  com

    return null;
}

From source file:org.syncany.crypto.specs.AesGcmCipherSpec.java

License:Open Source License

@Override
public OutputStream newCipherOutputStream(OutputStream underlyingOutputStream, byte[] secretKey, byte[] iv)
        throws CipherException {
    AEADBlockCipher cipher = new GCMBlockCipher(new AESEngine());
    cipher.init(true, new AEADParameters(new KeyParameter(secretKey), MAC_SIZE, iv));

    return new org.bouncycastle.crypto.io.CipherOutputStream(underlyingOutputStream, cipher);
}

From source file:org.syncany.crypto.specs.AesGcmCipherSpec.java

License:Open Source License

@Override
public InputStream newCipherInputStream(InputStream underlyingInputStream, byte[] secretKey, byte[] iv)
        throws CipherException {
    AEADBlockCipher cipher = new GCMBlockCipher(new AESEngine());
    cipher.init(false, new AEADParameters(new KeyParameter(secretKey), MAC_SIZE, iv));

    return new org.bouncycastle.crypto.io.CipherInputStream(underlyingInputStream, cipher);
}

From source file:org.syncany.tests.crypto.AesGcmWithBcInputStreamTest.java

License:Open Source License

@Test
public void testD_BouncyCastleCipherInputStreamWithAesGcm()
        throws InvalidKeyException, InvalidAlgorithmParameterException, IOException, NoSuchAlgorithmException,
        NoSuchProviderException, NoSuchPaddingException {
    // Encrypt (not interesting in this example)
    byte[] randomKey = createRandomArray(16);
    byte[] randomIv = createRandomArray(16);
    byte[] originalPlaintext = "Confirm 100$ pay".getBytes("ASCII");
    byte[] originalCiphertext = encryptWithAesGcm(originalPlaintext, randomKey, randomIv);

    // Attack / alter ciphertext (an attacker would do this!) 
    byte[] alteredCiphertext = Arrays.clone(originalCiphertext);
    alteredCiphertext[8] = (byte) (alteredCiphertext[8] ^ 0x08); // <<< Change 100$ to 900$

    // Decrypt with BouncyCastle implementation of CipherInputStream
    AEADBlockCipher cipher = new GCMBlockCipher(new AESEngine());
    cipher.init(false, new AEADParameters(new KeyParameter(randomKey), 128, randomIv));

    try {//from w ww  .  j av  a 2s. c  om
        readFromStream(new org.bouncycastle.crypto.io.CipherInputStream(
                new ByteArrayInputStream(alteredCiphertext), cipher));
        //             ^^^^^^^^^^^^^^^ INTERESTING PART ^^^^^^^^^^^^^^^^   
        //
        //  The BouncyCastle implementation of the CipherInputStream detects MAC verification errors and
        //  throws a InvalidCipherTextIOException if an error occurs. Nice! A more or less minor issue
        //  however is that it is incompatible with the standard JCE Cipher class from the javax.crypto 
        //  package. The new interface AEADBlockCipher must be used. The code below is not executed.      

        fail("Test D: org.bouncycastle.crypto.io.CipherInputStream:        NOT OK, tampering not detected");
    } catch (InvalidCipherTextIOException e) {
        System.out
                .println("Test D: org.bouncycastle.crypto.io.CipherInputStream:        OK, tampering detected");
    }
}