Java Code Examples for org.bouncycastle.crypto.BufferedBlockCipher#doFinal()

The following examples show how to use org.bouncycastle.crypto.BufferedBlockCipher#doFinal() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: BouncyCastleV1CryptoProvider.java    From paseto with MIT License 6 votes vote down vote up
@Override
public byte[] aes256CtrEncrypt(byte[] m, byte[] key, byte[] iv) {
	validateAes256CtrEncrypt(m, key, iv);

	try {
		BufferedBlockCipher cipher = ase256CtrCipher(true, key, iv);

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

		return cipherText;
	} catch (InvalidCipherTextException e) {
		// Not possible since we're not using padding.
		throw new CryptoProviderException("Invalid cipher text in aes256CtrEncrypt.", e);
	}
}
 
Example 2
Source File: BouncyCastleV1CryptoProvider.java    From paseto with MIT License 6 votes vote down vote up
@Override
public byte[] aes256CtrDecrypt(byte[] c, byte[] key, byte[] iv) {
	validateAes256CtrDecrypt(c, key, iv);

	try {
		BufferedBlockCipher cipher = ase256CtrCipher(false, key, iv);

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

		return clearText;
	} catch (InvalidCipherTextException e) {
		// Not possible since we're not using padding.
		throw new CryptoProviderException("Invalid cipher text in aes256CtrDecrypt.", e);
	}
}
 
Example 3
Source File: AESEncrypt.java    From nuls-v2 with MIT License 6 votes vote down vote up
/**
 * 数据通过KeyParameter和初始化向量加密
 *
 * @param plainBytes 需要加密的数据
 * @param iv         初始化向量
 * @param aesKey     秘钥
 * @return 加密后的数据
 */
public static EncryptedData encrypt(byte[] plainBytes, byte[] iv, KeyParameter aesKey) throws RuntimeException {
    HexUtil.checkNotNull(plainBytes);
    HexUtil.checkNotNull(aesKey);
    try {
        if (iv == null) {
            iv = EncryptedData.DEFAULT_IV;
            //SECURE_RANDOM.nextBytes(iv);
        }
        ParametersWithIV keyWithIv = new ParametersWithIV(aesKey, iv);
        // Encrypt using AES.
        BufferedBlockCipher cipher = new PaddedBufferedBlockCipher(new CBCBlockCipher(new AESFastEngine()));
        cipher.init(true, keyWithIv);
        byte[] encryptedBytes = new byte[cipher.getOutputSize(plainBytes.length)];
        final int length1 = cipher.processBytes(plainBytes, 0, plainBytes.length, encryptedBytes, 0);
        final int length2 = cipher.doFinal(encryptedBytes, length1);

        return new EncryptedData(iv, Arrays.copyOf(encryptedBytes, length1 + length2));
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}
 
Example 4
Source File: AESEncrypt.java    From nuls-v2 with MIT License 6 votes vote down vote up
/**
 * 数据通过KeyParameter解密
 *
 * @param dataToDecrypt 需要解密的数据
 * @param aesKey        秘钥
 * @return 解密后的数据
 */
public static byte[] decrypt(EncryptedData dataToDecrypt, KeyParameter aesKey) throws CryptoException {
    HexUtil.checkNotNull(dataToDecrypt);
    HexUtil.checkNotNull(aesKey);

    try {
        ParametersWithIV keyWithIv = new ParametersWithIV(new KeyParameter(aesKey.getKey()), dataToDecrypt.getInitialisationVector());

        // Decrypt the validator.
        BufferedBlockCipher cipher = new PaddedBufferedBlockCipher(new CBCBlockCipher(new AESFastEngine()));
        cipher.init(false, keyWithIv);

        byte[] cipherBytes = dataToDecrypt.getEncryptedBytes();
        byte[] decryptedBytes = new byte[cipher.getOutputSize(cipherBytes.length)];
        final int length1 = cipher.processBytes(cipherBytes, 0, cipherBytes.length, decryptedBytes, 0);
        final int length2 = cipher.doFinal(decryptedBytes, length1);

        return Arrays.copyOf(decryptedBytes, length1 + length2);
    } catch (Exception e) {
        throw new CryptoException();
    }
}
 
Example 5
Source File: UploadEncryptFileController.java    From Spring-MVC-Blueprints with MIT License 6 votes vote down vote up
private byte[] encryptDESFile(String keys, byte[] plainText) {
BlockCipher engine = new DESEngine();

      byte[] key = keys.getBytes();
      byte[] ptBytes = plainText;
      BufferedBlockCipher cipher = new PaddedBufferedBlockCipher(new CBCBlockCipher(engine));
      cipher.init(true, new KeyParameter(key));
      byte[] rv = new byte[cipher.getOutputSize(ptBytes.length)];
      int tam = cipher.processBytes(ptBytes, 0, ptBytes.length, rv, 0);
      try {
          cipher.doFinal(rv, tam);
      } catch (Exception ce) {
          ce.printStackTrace();
      }
      return rv;
  }
 
Example 6
Source File: Metodos.java    From ExamplesAndroid with Apache License 2.0 6 votes vote down vote up
public String testEncryptRijndael(String value,String key) throws DataLengthException, IllegalStateException, InvalidCipherTextException {
    BlockCipher engine = new RijndaelEngine(256);
    BufferedBlockCipher cipher = new PaddedBufferedBlockCipher(new CBCBlockCipher(engine), new ZeroBytePadding());

    byte[] keyBytes = key.getBytes();
    cipher.init(true, new KeyParameter(keyBytes));

    byte[] input = value.getBytes();
    byte[] cipherText = new byte[cipher.getOutputSize(input.length)];

    int cipherLength = cipher.processBytes(input, 0, input.length, cipherText, 0);
    cipher.doFinal(cipherText, cipherLength);

    String result = new String(Base64.encode(cipherText));
    //Log.e("testEncryptRijndael : " , result);
    return  result;
}
 
Example 7
Source File: AESBouncycastleUtils.java    From super-cloudops with Apache License 2.0 5 votes vote down vote up
/**
 * Method for AES ECB operation, internal call
 * 
 * @param key
 * @param src
 * @param encrypting
 * @return
 * @throws GeneralSecurityException
 */
private static byte[] doAESECB(byte[] key, byte[] src, boolean encrypting) throws GeneralSecurityException {
	byte[] result = new byte[src.length];
	try {
		BufferedBlockCipher engine = new BufferedBlockCipher(new AESEngine());
		engine.init(encrypting, new KeyParameter(key));
		int len = engine.processBytes(src, 0, src.length, result, 0);
		engine.doFinal(result, len);
	} catch (InvalidCipherTextException e) {
		throw new GeneralSecurityException(e);
	}
	return result;
}
 
Example 8
Source File: AESBouncycastleUtils.java    From super-cloudops with Apache License 2.0 5 votes vote down vote up
/**
 * Method for AES CBC operation, internal call
 * 
 * @param key
 * @param icv
 * @param src
 * @param encrypting
 * @return
 * @throws GeneralSecurityException
 */
private static byte[] doAESCBC(byte[] key, byte[] icv, byte[] src, boolean encrypting) throws GeneralSecurityException {
	byte[] result = new byte[src.length];
	try {
		BufferedBlockCipher engine = new BufferedBlockCipher(new CBCBlockCipher(new AESEngine()));
		engine.init(encrypting, new ParametersWithIV(new KeyParameter(key), icv));
		int len = engine.processBytes(src, 0, src.length, result, 0);
		engine.doFinal(result, len);
	} catch (InvalidCipherTextException e) {
		throw new GeneralSecurityException(e);
	}
	return result;
}
 
Example 9
Source File: DownloadDecryptFileController.java    From Spring-MVC-Blueprints with MIT License 5 votes vote down vote up
public byte[] decryptDESFile(String key, byte[] cipherText) {
BlockCipher engine = new DESEngine();
      byte[] bytes = key.getBytes();
      BufferedBlockCipher cipher = new PaddedBufferedBlockCipher(new CBCBlockCipher(engine));
      cipher.init(false, new KeyParameter(bytes));
      byte[] rv = new byte[cipher.getOutputSize(cipherText.length)];
      int tam = cipher.processBytes(cipherText, 0, cipherText.length, rv, 0);
      try {
          cipher.doFinal(rv, tam);
      } catch (Exception ce) {
          ce.printStackTrace();
      }
      return rv;
  }
 
Example 10
Source File: Metodos.java    From ExamplesAndroid with Apache License 2.0 5 votes vote down vote up
public String testDecryptRijndael(String value,String key) throws DataLengthException, IllegalStateException, InvalidCipherTextException {
        BlockCipher engine = new RijndaelEngine(256);
        BufferedBlockCipher cipher = new PaddedBufferedBlockCipher(new CBCBlockCipher(engine), new ZeroBytePadding());

        byte[] keyBytes = key.getBytes();
        cipher.init(false, new KeyParameter(keyBytes));

        byte[] output = Base64.decode(value.getBytes());
        byte[] cipherText = new byte[cipher.getOutputSize(output.length)];

        int cipherLength = cipher.processBytes(output, 0, output.length, cipherText, 0);
        int outputLength = cipher.doFinal(cipherText, cipherLength);
        outputLength += cipherLength;

        byte[] resultBytes = cipherText;
        if (outputLength != output.length) {
            resultBytes = new byte[outputLength];
            System.arraycopy(
                    cipherText, 0,
                    resultBytes, 0,
                    outputLength
            );
        }

        String result = new String(resultBytes);
return  result;
    }
 
Example 11
Source File: StandardSecurityHandler.java    From sambox with Apache License 2.0 5 votes vote down vote up
private void validatePerms(PDEncryption encryption, int dicPermissions, boolean encryptMetadata)
        throws IOException
{
    try
    {
        BufferedBlockCipher cipher = new BufferedBlockCipher(new AESFastEngine());
        cipher.init(false, new KeyParameter(getEncryptionKey()));

        byte[] buf = new byte[cipher.getOutputSize(encryption.getPerms().length)];
        int len = cipher.processBytes(encryption.getPerms(), 0, encryption.getPerms().length,
                buf, 0);
        len += cipher.doFinal(buf, len);
        byte[] perms = copyOf(buf, len);

        if (perms[9] != 'a' || perms[10] != 'd' || perms[11] != 'b')
        {
            LOG.warn("Verification of permissions failed (constant)");
        }

        int permsP = perms[0] & 0xFF | (perms[1] & 0xFF) << 8 | (perms[2] & 0xFF) << 16
                | (perms[3] & 0xFF) << 24;

        if (permsP != dicPermissions)
        {
            LOG.warn("Verification of permissions failed (" + String.format("%08X", permsP)
                    + " != " + String.format("%08X", dicPermissions) + ")");
        }

        if (encryptMetadata && perms[8] != 'T' || !encryptMetadata && perms[8] != 'F')
        {
            LOG.warn("Verification of permissions failed (EncryptMetadata)");
        }
    }
    catch (DataLengthException | IllegalStateException | InvalidCipherTextException e)
    {
        throw new IOException(e);
    }
}
 
Example 12
Source File: StandardSecurityHandler.java    From sambox with Apache License 2.0 4 votes vote down vote up
private byte[] computeEncryptedKeyRev56(byte[] password, boolean isOwnerPassword, byte[] o,
        byte[] u, byte[] oe, byte[] ue, int encRevision) throws IOException
{
    byte[] hash, fileKeyEnc;

    if (isOwnerPassword)
    {
        byte[] oKeySalt = new byte[8];
        System.arraycopy(o, 40, oKeySalt, 0, 8);

        if (encRevision == 5)
        {
            hash = computeSHA256(password, oKeySalt, u);
        }
        else
        {
            hash = computeHash2A(password, oKeySalt, u);
        }

        fileKeyEnc = oe;
    }
    else
    {
        byte[] uKeySalt = new byte[8];
        System.arraycopy(u, 40, uKeySalt, 0, 8);

        if (encRevision == 5)
        {
            hash = computeSHA256(password, uKeySalt, null);
        }
        else
        {
            hash = computeHash2A(password, uKeySalt, null);
        }

        fileKeyEnc = ue;
    }
    try
    {
        BufferedBlockCipher cipher = new BufferedBlockCipher(
                new CBCBlockCipher(new AESFastEngine()));
        cipher.init(false, new KeyParameter(hash));
        byte[] buf = new byte[cipher.getOutputSize(fileKeyEnc.length)];
        int len = cipher.processBytes(fileKeyEnc, 0, fileKeyEnc.length, buf, 0);
        len += cipher.doFinal(buf, len);
        return copyOf(buf, len);
    }
    catch (DataLengthException | IllegalStateException | InvalidCipherTextException e)
    {
        throw new IOException(e);
    }
}