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:com.skplanet.jose.jwa.crypto.CryptoUtils.java

License:Open Source License

public static byte[] aesGcmDecrypt(Transformation transformation, byte[] encryptedData, byte[] secret,
        int atLength, byte[] iv, byte[] aad) throws Exception {
    BlockCipher blockCipher = new AESEngine();
    blockCipher.init(false, new KeyParameter(new SecretKeySpec(secret, "AES").getEncoded()));

    GCMBlockCipher aGCMBlockCipher = new GCMBlockCipher(blockCipher);
    aGCMBlockCipher.init(false, new AEADParameters(new KeyParameter(secret), atLength, iv, aad));

    int len = aGCMBlockCipher.getOutputSize(encryptedData.length);
    byte[] out = new byte[len];
    int outOff = aGCMBlockCipher.processBytes(encryptedData, 0, encryptedData.length, out, 0);
    aGCMBlockCipher.doFinal(out, outOff);

    return out;/*from  ww  w.j  a v a 2 s .  co  m*/
}

From source file:com.sos.CredentialStore.KeePass.pl.sind.keepass.crypto.BcAESCipher.java

License:Apache License

@Override
public byte[] decrypt(final byte[] key, final byte[] data, final byte[] iv) throws CipherException {
    BufferedBlockCipher cipher = new PaddedBufferedBlockCipher(new CBCBlockCipher(new AESEngine()));

    if (iv != null) {
        cipher.init(false, new ParametersWithIV(new KeyParameter(key), iv));
    } else {/*www  .ja  v  a 2s .  c  o m*/
        cipher.init(false, new KeyParameter(key));
    }

    byte[] decoded = new byte[cipher.getOutputSize(data.length)];

    int out = cipher.processBytes(data, 0, data.length, decoded, 0);
    try {
        out += cipher.doFinal(decoded, out);

        if (out < decoded.length) {
            decoded = Arrays.copyOf(decoded, out);
        }

    } catch (DataLengthException e) {
        // we are padding so shouldn happen
        throw new CipherException("Invalid data lenght", e);
    } catch (IllegalStateException e) {
        throw new CipherException("Decrypting error", e);
    } catch (InvalidCipherTextException e) {
        throw new CipherException("Unable to decrypt data", e);
    }

    return decoded;

}

From source file:com.sos.CredentialStore.KeePass.pl.sind.keepass.crypto.BcAESCipher.java

License:Apache License

@Override
public byte[] encrypt(final byte[] key, final byte[] data, final byte[] iv, final int rounds,
        final boolean padding) throws CipherException {
    BufferedBlockCipher cipher = null;//  w  ww .  j ava 2s  .c o m

    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));
    }

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

    int out = cipher.processBytes(data, 0, data.length, encoded, 0);
    if (rounds > 1) {
        for (int i = 1; i < rounds; i++) {
            out = cipher.processBytes(encoded, 0, encoded.length, encoded, 0);
        }
    }

    try {
        if (padding && out < encoded.length) {
            cipher.doFinal(encoded, out);
        }
    } catch (DataLengthException e) {
        // we are padding so shouldn happen
        throw new CipherException("Invalid data lenght", e);
    } catch (IllegalStateException e) {
        throw new CipherException("Decrypting error", e);
    } catch (InvalidCipherTextException e) {
        throw new CipherException("Unable to decrypt data", e);
    }

    return encoded;
}

From source file:com.thecorpora.qbo.androidapk.AESCipher.java

License:Open Source License

public String encrypt(byte configData[], String key) throws Exception {
    byte[] encryptedConfigData = null;
    AESEngine blockCipher = new AESEngine();
    blockCipher.reset();// www .j  a v a 2  s  .  c  o m
    CBCBlockCipher cbcCipher = new CBCBlockCipher(blockCipher);
    BufferedBlockCipher bbc = new PaddedBufferedBlockCipher(cbcCipher);

    byte[] salt = new byte[8];
    SecureRandom secure = new SecureRandom();
    secure.nextBytes(salt);

    //intialising in the encryption mode with Key and IV
    bbc.init(true, getKeyParamWithIv(key, salt));
    byte[] encryptedData = new byte[bbc.getOutputSize(configData.length)];

    //process array of bytes
    int noOfBytes = bbc.processBytes(configData, 0, configData.length, encryptedData, 0);

    //process the last block in the buffer
    bbc.doFinal(encryptedData, noOfBytes);

    ByteArrayOutputStream bos = new ByteArrayOutputStream();
    //writing encrypted data along with the salt in the format readable by open ssl api
    bos.write("Salted__".getBytes());
    bos.write(salt);
    bos.write(encryptedData);
    encryptedConfigData = bos.toByteArray();
    bos.close();

    //      return encryptedConfigData;
    return Base64.encodeToString(encryptedConfigData, Base64.DEFAULT);

}

From source file:com.vmware.admiral.common.security.EncryptorService.java

License:Open Source License

private BufferedBlockCipher getCipher(boolean forEncryption) {
    BufferedBlockCipher cipher = new PaddedBufferedBlockCipher(new CBCBlockCipher(new AESEngine()),
            new PKCS7Padding());
    cipher.init(forEncryption, new ParametersWithIV(
            new KeyParameter(keyBytes, IV_LENGTH, keyBytes.length - IV_LENGTH), keyBytes, 0, IV_LENGTH));
    return cipher;
}

From source file:com.wlami.mibox.core.encryption.AesEncryption.java

License:Open Source License

/**
 * Encrypts and decrypts a byte array.// w w w . j  a  va  2  s.c om
 * 
 * @param encrypt
 *            <code>true</code> for encryption <br/>
 *            <code>false</code> for decryption
 * @param ciphertext
 *            the data which shall be decrypted or encrypted
 * @param initVector
 *            the iv
 * @param key
 *            the key
 * @return an encrypted /decrypted byte array
 * @throws CryptoException
 */
public static byte[] crypt(boolean encrypt, byte[] ciphertext, byte[] initVector, byte[] key)
        throws InvalidCipherTextException {
    log.debug("starting " + (encrypt ? "encryption" : "decryption"));
    BlockCipher engine = new AESEngine();
    PaddedBufferedBlockCipher cipher = new PaddedBufferedBlockCipher(new CBCBlockCipher(engine));
    log.debug("retrieved an AESEngine");
    cipher.init(encrypt, new ParametersWithIV(new KeyParameter(key), initVector));
    byte[] cipherArray = new byte[cipher.getOutputSize(ciphertext.length)];
    log.debug("creatied cipherArray with size " + cipherArray.length + "\n encryption...");
    int outputByteCount = cipher.processBytes(ciphertext, 0, ciphertext.length, cipherArray, 0);
    log.debug("finalizing cipher");
    outputByteCount += cipher.doFinal(cipherArray, outputByteCount);
    byte[] result = new byte[outputByteCount];
    System.arraycopy(cipherArray, 0, result, 0, outputByteCount);
    return result;
}

From source file:com._17od.upm.crypto.EncryptionService.java

License:Open Source License

public void initCipher(char[] password) throws InvalidPasswordException, NoSuchAlgorithmException,
        NoSuchPaddingException, InvalidKeyException, Exception {

    try {//w  w w  .  ja va2s . c o  m
        //Establishing Secure Channel
        SecureChannel(password);
        //SecureChannel();

        //Asking Card to be ready with Symm Key
        byte[] Data = new byte[password.length + salt.length];
        System.arraycopy(password.toString().getBytes(), 0, Data, 0, password.length);
        System.arraycopy(salt, 0, Data, password.length, salt.length);
        InterFaceApplet.SendAppletInstructionSecureChannel(PCSideCardInterface.SEND_INS_GENKEY, (byte) 0,
                (byte) 0, Data);

        //Generate Nounce for PC
        N_1 = generateSalt();
        byte[] Temp = new byte[N_1.length + 16];
        System.arraycopy(N_1, 0, Temp, 0, N_1.length);
        System.arraycopy("AAAAAAAAAAAAAAAA".getBytes(), 0, Temp, N_1.length, 16);
        byte[] res = new byte[32];
        cipher.doFinal(Temp, 0, 32, res, 0);

        //Send Ek(Nounce_PC || ID of PC)
        ResponseFromCard = InterFaceApplet.SendAppletInstructionSecureChannel(PCSideCardInterface.SEND_INS_N_1,
                (byte) 0, (byte) 0, res);

        //Received response from Card Nounce_PC || Nounce_Card || ID of Card

        //Decrypting Card Nounce
        cipher.init(Cipher.DECRYPT_MODE, secretKeySpec);
        byte[] res1 = new byte[48];
        cipher.doFinal(ResponseFromCard, 0, 48, res1, 0);

        //Copying Nounce_PC
        byte[] res2 = new byte[16];
        System.arraycopy(res1, 0, res2, 0, 16);

        for (short i = 0; i < N_1.length; i++) {
            if (res2[i] != N_1[i]) {
                //If Nounce_PC is not matching throw error
                /*throw exception*/
                JOptionPane.showMessageDialog(mainWindow, Translator.translate("SecureChProblem"));
                System.exit(0);
            }
        }

        //Copying Nounce_Card
        System.arraycopy(res1, 16, N_B, 0, 16);

        cipher.init(Cipher.ENCRYPT_MODE, secretKeySpec);

        cipher.doFinal(N_B, 0, 16, res2, 0);

        //Send Ek(Nounce_Card) 
        ResponseFromCard = InterFaceApplet.SendAppletInstructionSecureChannel(PCSideCardInterface.SEND_INS_N_B,
                (byte) 0, (byte) 0, res2);
        //Checking response from card for Nounce_Card
        if (ResponseFromCard == null) {
            //If Nounce_Card is not matching throw error
            /*throw exception*/
            JOptionPane.showMessageDialog(mainWindow, Translator.translate("SecureChProblem"));
            System.exit(0);
        }
        //Nounce_Card is Verified, then Generate Session Key      
        byte[] SessionKey = new byte[16];
        System.arraycopy(N_1, 0, res, 0, 16);
        System.arraycopy(N_B, 0, res, 16, 16);

        //HASH(Nounce_PC || Nounce_Card)
        MessageDigest sha = MessageDigest.getInstance("SHA-1");
        SessionKey = Arrays.copyOf(sha.digest(res), 16);

        //Initialing AES with Session Key
        sessionKeySpec = new SecretKeySpec(SessionKey, "AES");

        SKcipher = Cipher.getInstance("AES/ECB/NOPADDING");

        SKcipher.init(Cipher.DECRYPT_MODE, sessionKeySpec);

        //For New Database
        if (FileHandle == null) {
            //Asking for Handle from Card            
            FileHandle = InterFaceApplet.SendAppletInstruction(PCSideCardInterface.SEND_INS_SETKEY, (byte) 0,
                    (byte) 0, null, password);
        }
        //Asking Key from Card
        byte[] KeyFromCard1 = InterFaceApplet.SendAppletInstruction(PCSideCardInterface.SEND_INS_GETKEY,
                (byte) 0, (byte) 0, FileHandle, password);

        //Extracting Key from Card           
        System.arraycopy(KeyFromCard1, (short) 0, KeyFromCard, (short) 0, (short) 1);
        //Decrypting the key using Session Key
        SKcipher.doFinal(KeyFromCard1, (short) 1, (short) (KeyFromCard1.length - 1), KeyFromCard, (short) 1);

    } catch (InvalidPasswordException ex) {
        throw ex;
    }

    //Encryption/Decryption operation        
    KeyParameter keyParams = new KeyParameter(Util.cutArray(KeyFromCard, FileHandle_LENGTH, KeyLengthAES));

    encryptCipher = new PaddedBufferedBlockCipher(new CBCBlockCipher(new AESEngine()), new PKCS7Padding());
    encryptCipher.init(true, keyParams);
    decryptCipher = new PaddedBufferedBlockCipher(new CBCBlockCipher(new AESEngine()), new PKCS7Padding());
    decryptCipher.init(false, keyParams);

}

From source file:dbn.crypto.Crypto.java

public static byte[] aesEncrypt(byte[] plaintext, byte[] key) {
    try {//www  .j av a 2 s. co  m
        byte[] iv = new byte[16];
        secureRandom.get().nextBytes(iv);
        PaddedBufferedBlockCipher aes = new PaddedBufferedBlockCipher(new CBCBlockCipher(new AESEngine()));
        CipherParameters ivAndKey = new ParametersWithIV(new KeyParameter(key), iv);
        aes.init(true, ivAndKey);
        byte[] output = new byte[aes.getOutputSize(plaintext.length)];
        int ciphertextLength = aes.processBytes(plaintext, 0, plaintext.length, output, 0);
        ciphertextLength += aes.doFinal(output, ciphertextLength);
        byte[] result = new byte[iv.length + ciphertextLength];
        System.arraycopy(iv, 0, result, 0, iv.length);
        System.arraycopy(output, 0, result, iv.length, ciphertextLength);
        return result;
    } catch (InvalidCipherTextException e) {
        throw new RuntimeException(e.getMessage(), e);
    }
}

From source file:dbn.crypto.Crypto.java

public static byte[] aesGCMEncrypt(byte[] plaintext, byte[] key) {
    try {//from  w w  w. ja  v  a 2 s .  c o  m
        byte[] iv = new byte[16];
        secureRandom.get().nextBytes(iv);
        GCMBlockCipher aes = new GCMBlockCipher(new AESEngine());
        CipherParameters ivAndKey = new ParametersWithIV(new KeyParameter(key), iv);
        aes.init(true, ivAndKey);
        byte[] output = new byte[aes.getOutputSize(plaintext.length)];
        int ciphertextLength = aes.processBytes(plaintext, 0, plaintext.length, output, 0);
        ciphertextLength += aes.doFinal(output, ciphertextLength);
        byte[] result = new byte[iv.length + ciphertextLength];
        System.arraycopy(iv, 0, result, 0, iv.length);
        System.arraycopy(output, 0, result, iv.length, ciphertextLength);
        return result;
    } catch (InvalidCipherTextException e) {
        throw new RuntimeException(e.getMessage(), e);
    }
}

From source file:dbn.crypto.Crypto.java

public static byte[] aesDecrypt(byte[] ivCiphertext, byte[] key) {
    try {/* ww  w.  j  ava 2 s. com*/
        if (ivCiphertext.length < 16 || ivCiphertext.length % 16 != 0) {
            throw new InvalidCipherTextException("invalid ivCiphertext length");
        }
        byte[] iv = Arrays.copyOfRange(ivCiphertext, 0, 16);
        byte[] ciphertext = Arrays.copyOfRange(ivCiphertext, 16, ivCiphertext.length);
        PaddedBufferedBlockCipher aes = new PaddedBufferedBlockCipher(new CBCBlockCipher(new AESEngine()));
        CipherParameters ivAndKey = new ParametersWithIV(new KeyParameter(key), iv);
        aes.init(false, ivAndKey);
        byte[] output = new byte[aes.getOutputSize(ciphertext.length)];
        int plaintextLength = aes.processBytes(ciphertext, 0, ciphertext.length, output, 0);
        plaintextLength += aes.doFinal(output, plaintextLength);
        byte[] result = new byte[plaintextLength];
        System.arraycopy(output, 0, result, 0, result.length);
        return result;
    } catch (InvalidCipherTextException e) {
        throw new RuntimeException(e.getMessage(), e);
    }
}