org.bouncycastle.crypto.BufferedBlockCipher Java Examples

The following examples show how to use org.bouncycastle.crypto.BufferedBlockCipher. 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: 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 #2
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 #3
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 #4
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 #5
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 #6
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 #7
Source File: Ed25519BlockCipher.java    From symbol-sdk-java with Apache License 2.0 6 votes vote down vote up
@Override
@SuppressWarnings("squid:S1168")
public byte[] encrypt(final byte[] input) {
    // Setup salt.

    // Derive shared key.
    final byte[] sharedKey = getSharedKey(this.senderKeyPair.getPrivateKey(),
        this.recipientKeyPair.getPublicKey());

    // Setup IV.
    final byte[] ivData = RandomUtils.generateRandomBytes(IV_LENGTH);

    // Setup block cipher.
    final BufferedBlockCipher cipher = setupBlockCipher(sharedKey, ivData, true);

    // Encode.
    final byte[] buf = transform(cipher, input);
    if (null == buf) {
        return null;
    }

    final byte[] result = new byte[ivData.length + buf.length];
    System.arraycopy(ivData, 0, result, 0, ivData.length);
    System.arraycopy(buf, 0, result, ivData.length, buf.length);
    return result;
}
 
Example #8
Source File: Ed25519BlockCipher.java    From symbol-sdk-java with Apache License 2.0 6 votes vote down vote up
@Override
@SuppressWarnings("squid:S1168")
public byte[] decrypt(final byte[] input) {
    if (input.length < 32) {
        return null;
    }

    final byte[] ivData = Arrays.copyOfRange(input, 0, IV_LENGTH);
    final byte[] encData = Arrays.copyOfRange(input, IV_LENGTH, input.length);

    // Derive shared key.
    final byte[] sharedKey = getSharedKey(this.recipientKeyPair.getPrivateKey(),
        this.senderKeyPair.getPublicKey());

    // Setup block cipher.
    final BufferedBlockCipher cipher = setupBlockCipher(sharedKey, ivData, false);

    // Decode.
    return transform(cipher, encData);
}
 
Example #9
Source File: Ed25519BlockCipherVectorTester.java    From symbol-sdk-java with Apache License 2.0 6 votes vote down vote up
@ParameterizedTest
@MethodSource("testResolveSharedKey")
void testResolveSharedKey(String privateKey, String otherPublicKey,
    String iv, String cipherText, String clearText) {
    PrivateKey privateKeyObject = PrivateKey.fromHexString(privateKey);
    PublicKey otherPublicKeyObject = PublicKey.fromHexString(otherPublicKey);
    byte[] sharedKey = Ed25519BlockCipher.getSharedKey(
        privateKeyObject,
        otherPublicKeyObject
    );

    final BufferedBlockCipher cipher = Ed25519BlockCipher
        .setupBlockCipher(sharedKey, ConvertUtils.fromHexToBytes(iv), false);
    byte[] decrypted = Ed25519BlockCipher
        .transform(cipher, ConvertUtils.fromHexToBytes(cipherText));
    Assertions.assertNotNull(decrypted);
    Assertions
        .assertEquals(clearText.toUpperCase(), ConvertUtils.toHex(decrypted).toUpperCase());
}
 
Example #10
Source File: RLPxConnectionFactory.java    From incubator-tuweni with Apache License 2.0 5 votes vote down vote up
private static EthereumIESEncryptionEngine forDecryption(
    SecretKey privateKey,
    PublicKey ephemeralPublicKey,
    Bytes iv,
    Bytes commonMac) {
  CipherParameters pubParam = new ECPublicKeyParameters(ephemeralPublicKey.asEcPoint(), CURVE);
  CipherParameters privParam = new ECPrivateKeyParameters(privateKey.bytes().toUnsignedBigInteger(), CURVE);

  BasicAgreement agreement = new ECDHBasicAgreement();
  agreement.init(privParam);
  byte[] agreementValue =
      BigIntegers.asUnsignedByteArray(agreement.getFieldSize(), agreement.calculateAgreement(pubParam));

  IESWithCipherParameters iesWithCipherParameters = new IESWithCipherParameters(new byte[0], new byte[0], 128, 128);

  EthereumIESEncryptionEngine.ECIESHandshakeKDFFunction kdf =
      new EthereumIESEncryptionEngine.ECIESHandshakeKDFFunction(1, new SHA256Digest());
  kdf.init(new KDFParameters(agreementValue, iesWithCipherParameters.getDerivationV()));
  EthereumIESEncryptionEngine engine = new EthereumIESEncryptionEngine(
      agreement,
      kdf,
      new HMac(new SHA256Digest()),
      commonMac.toArrayUnsafe(),
      new BufferedBlockCipher(new SICBlockCipher(new AESEngine())));
  ParametersWithIV cipherParameters = new ParametersWithIV(iesWithCipherParameters, iv.toArrayUnsafe());
  engine.init(false, privParam, pubParam, cipherParameters);
  return engine;
}
 
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: 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 #13
Source File: CipherWriteStreamValidation.java    From sfs with Apache License 2.0 5 votes vote down vote up
/**
 * Constructs a CipherOutputStream from an OutputStream and a
 * BufferedBlockCipher.
 */
public CipherOutputStream(
        OutputStream os,
        BufferedBlockCipher cipher) {
    super(os);
    this.bufferedBlockCipher = cipher;
}
 
Example #14
Source File: CipherWriteStreamValidation.java    From sfs with Apache License 2.0 5 votes vote down vote up
/**
 * Constructs a CipherInputStream from an InputStream and a
 * BufferedBlockCipher.
 */
public CipherInputStream(
        InputStream is,
        BufferedBlockCipher cipher) {
    super(is);

    this.bufferedBlockCipher = cipher;

    int outSize = cipher.getOutputSize(INPUT_BUF_SIZE);

    buf = new byte[(outSize > INPUT_BUF_SIZE) ? outSize : INPUT_BUF_SIZE];
    inBuf = new byte[INPUT_BUF_SIZE];
}
 
Example #15
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 #16
Source File: Ed25519BlockCipher.java    From symbol-sdk-java with Apache License 2.0 5 votes vote down vote up
public static BufferedBlockCipher setupBlockCipher(
    final byte[] sharedKey, final byte[] ivData, final boolean forEncryption) {
    // Setup cipher parameters with key and IV.
    final KeyParameter keyParam = new KeyParameter(sharedKey);
    final CipherParameters params = new ParametersWithIV(keyParam, ivData);

    // Setup AES cipher in CBC mode with PKCS7 padding.
    final BlockCipherPadding padding = new PKCS7Padding();
    final BufferedBlockCipher cipher =
        new PaddedBufferedBlockCipher(new CBCBlockCipher(new AESEngine()), padding);
    cipher.reset();
    cipher.init(forEncryption, params);
    return cipher;
}
 
Example #17
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 #18
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 #19
Source File: BouncyCastleV1CryptoProvider.java    From paseto with MIT License 5 votes vote down vote up
private BufferedBlockCipher ase256CtrCipher(boolean forEncryption, byte[] key, byte[] iv) {
	BlockCipher engine = new AESEngine();
	BufferedBlockCipher cipher = new BufferedBlockCipher(new SICBlockCipher(engine));
	CipherParameters params = new ParametersWithIV(new KeyParameter(key), iv);

	cipher.init(forEncryption, params);
	return cipher;
}
 
Example #20
Source File: RLPxConnectionFactory.java    From cava with Apache License 2.0 5 votes vote down vote up
private static EthereumIESEncryptionEngine forDecryption(
    SecretKey privateKey,
    PublicKey ephemeralPublicKey,
    Bytes iv,
    Bytes commonMac) {
  CipherParameters pubParam = new ECPublicKeyParameters(ephemeralPublicKey.asEcPoint(), CURVE);
  CipherParameters privParam = new ECPrivateKeyParameters(privateKey.bytes().toUnsignedBigInteger(), CURVE);

  BasicAgreement agreement = new ECDHBasicAgreement();
  agreement.init(privParam);
  byte[] agreementValue =
      BigIntegers.asUnsignedByteArray(agreement.getFieldSize(), agreement.calculateAgreement(pubParam));

  IESWithCipherParameters iesWithCipherParameters = new IESWithCipherParameters(new byte[0], new byte[0], 128, 128);

  EthereumIESEncryptionEngine.ECIESHandshakeKDFFunction kdf =
      new EthereumIESEncryptionEngine.ECIESHandshakeKDFFunction(1, new SHA256Digest());
  kdf.init(new KDFParameters(agreementValue, iesWithCipherParameters.getDerivationV()));
  EthereumIESEncryptionEngine engine = new EthereumIESEncryptionEngine(
      agreement,
      kdf,
      new HMac(new SHA256Digest()),
      commonMac.toArrayUnsafe(),
      new BufferedBlockCipher(new SICBlockCipher(new AESEngine())));
  ParametersWithIV cipherParameters = new ParametersWithIV(iesWithCipherParameters, iv.toArrayUnsafe());
  engine.init(false, privParam, pubParam, cipherParameters);
  return engine;
}
 
Example #21
Source File: RLPxConnectionFactory.java    From cava with Apache License 2.0 5 votes vote down vote up
private static EthereumIESEncryptionEngine forEncryption(
    PublicKey pubKey,
    Bytes iv,
    Bytes commonMac,
    KeyPair ephemeralKeyPair) {
  CipherParameters pubParam = new ECPublicKeyParameters(pubKey.asEcPoint(), CURVE);
  CipherParameters privParam =
      new ECPrivateKeyParameters(ephemeralKeyPair.secretKey().bytes().toUnsignedBigInteger(), CURVE);

  BasicAgreement agree = new ECDHBasicAgreement();
  agree.init(privParam);
  BigInteger z = agree.calculateAgreement(pubParam);
  byte[] zbytes = BigIntegers.asUnsignedByteArray(agree.getFieldSize(), z);

  IESWithCipherParameters iesWithCipherParameters = new IESWithCipherParameters(new byte[0], new byte[0], 128, 128);

  // Initialise the KDF.
  EthereumIESEncryptionEngine.ECIESHandshakeKDFFunction kdf =
      new EthereumIESEncryptionEngine.ECIESHandshakeKDFFunction(1, new SHA256Digest());
  kdf.init(new KDFParameters(zbytes, iesWithCipherParameters.getDerivationV()));
  EthereumIESEncryptionEngine engine = new EthereumIESEncryptionEngine(
      agree,
      kdf,
      new HMac(new SHA256Digest()),
      commonMac.toArrayUnsafe(),
      new BufferedBlockCipher(new SICBlockCipher(new AESEngine())));
  ParametersWithIV cipherParameters = new ParametersWithIV(iesWithCipherParameters, iv.toArrayUnsafe());
  engine.init(true, privParam, pubParam, cipherParameters);

  return engine;
}
 
Example #22
Source File: CryptManager.java    From FishingBot with GNU General Public License v3.0 4 votes vote down vote up
/**
 * Create a new BufferedBlockCipher instance
 */
private static BufferedBlockCipher createBufferedBlockCipher(boolean par0, Key par1Key) {
    BufferedBlockCipher var2 = new BufferedBlockCipher(new CFBBlockCipher(new AESFastEngine(), 8));
    var2.init(par0, new ParametersWithIV(new KeyParameter(par1Key.getEncoded()), par1Key.getEncoded(), 0, 16));
    return var2;
}
 
Example #23
Source File: FileStreamWriter.java    From InflatableDonkey with MIT License 4 votes vote down vote up
static InputStream decryptStream(InputStream in, XFileKey keyCipher) {
    BlockCipher cipher = keyCipher.ciphers().get();
    cipher.init(false, new KeyParameter(keyCipher.key()));
    return new CipherInputStream(in, new BufferedBlockCipher(cipher));
}
 
Example #24
Source File: RLPxConnectionFactory.java    From incubator-tuweni with Apache License 2.0 4 votes vote down vote up
private static EthereumIESEncryptionEngine forEncryption(
    PublicKey pubKey,
    Bytes iv,
    Bytes commonMac,
    KeyPair ephemeralKeyPair) {
  CipherParameters pubParam = new ECPublicKeyParameters(pubKey.asEcPoint(), CURVE);
  CipherParameters privParam =
      new ECPrivateKeyParameters(ephemeralKeyPair.secretKey().bytes().toUnsignedBigInteger(), CURVE);

  BasicAgreement agree = new ECDHBasicAgreement();
  agree.init(privParam);
  BigInteger z = agree.calculateAgreement(pubParam);
  byte[] zbytes = BigIntegers.asUnsignedByteArray(agree.getFieldSize(), z);

  IESWithCipherParameters iesWithCipherParameters = new IESWithCipherParameters(new byte[0], new byte[0], 128, 128);

  // Initialise the KDF.
  EthereumIESEncryptionEngine.ECIESHandshakeKDFFunction kdf =
      new EthereumIESEncryptionEngine.ECIESHandshakeKDFFunction(1, new SHA256Digest());
  kdf.init(new KDFParameters(zbytes, iesWithCipherParameters.getDerivationV()));
  EthereumIESEncryptionEngine engine = new EthereumIESEncryptionEngine(
      agree,
      kdf,
      new HMac(new SHA256Digest()),
      commonMac.toArrayUnsafe(),
      new BufferedBlockCipher(new SICBlockCipher(new AESEngine())));
  ParametersWithIV cipherParameters = new ParametersWithIV(iesWithCipherParameters, iv.toArrayUnsafe());
  engine.init(true, privParam, pubParam, cipherParameters);

  return engine;
}
 
Example #25
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);
    }
}
 
Example #26
Source File: AESEngineNoPadding.java    From sambox with Apache License 2.0 4 votes vote down vote up
AESEngineNoPadding(BufferedBlockCipher cipher)
{
    this.cipher = cipher;
}
 
Example #27
Source File: AESEngineNoPadding.java    From sambox with Apache License 2.0 4 votes vote down vote up
/**
 * @return and instance of EncryptionAlgorithmEngine AES/CBC/NoPadding and no initialization vector
 */
static AESEngineNoPadding cbc()
{
    return new AESEngineNoPadding(
            new BufferedBlockCipher(new CBCBlockCipher(new AESFastEngine())));
}
 
Example #28
Source File: AESEngineNoPadding.java    From sambox with Apache License 2.0 4 votes vote down vote up
/**
 * @return and instance of EncryptionAlgorithmEngine AES/ECB/NoPadding and no initialization vector
 */
static AESEngineNoPadding ecb()
{
    return new AESEngineNoPadding(new BufferedBlockCipher(new AESFastEngine()));
}
 
Example #29
Source File: FileDecrypter.java    From LiquidDonkey with MIT License 4 votes vote down vote up
/**
 * Returns a new instance.
 *
 * @return a new instance, not null
 */
public static FileDecrypter create() {
    return FileDecrypter.from(
            new BufferedBlockCipher(new CBCBlockCipher(new AESEngine())),
            new SHA1Digest());
}
 
Example #30
Source File: FileDecrypter.java    From LiquidDonkey with MIT License 4 votes vote down vote up
static FileDecrypter from(BufferedBlockCipher cbcAes, SHA1Digest sha1) {
    return new FileDecrypter(cbcAes, sha1);
}