org.bouncycastle.crypto.engines.AESFastEngine Java Examples

The following examples show how to use org.bouncycastle.crypto.engines.AESFastEngine. 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: SecurityHandler.java    From sambox with Apache License 2.0 7 votes vote down vote up
/**
 * Encrypt or decrypt data with AES256.
 *
 * @param data The data to encrypt.
 * @param output The output to write the encrypted data to.
 *
 * @throws IOException If there is an error reading the data.
 */
private void decryptDataAES256(InputStream data, OutputStream output) throws IOException
{
    byte[] iv = new byte[16];

    // read IV from stream
    int ivSize = data.read(iv);
    if (ivSize == -1)
    {
        return;
    }

    if (ivSize != iv.length)
    {
        throw new IOException("AES initialization vector not fully read: only " + ivSize
                + " bytes read instead of " + iv.length);
    }
    PaddedBufferedBlockCipher cipher = new PaddedBufferedBlockCipher(
            new CBCBlockCipher(new AESFastEngine()));
    cipher.init(false, new ParametersWithIV(new KeyParameter(encryptionKey), iv));
    try (CipherInputStream cis = new CipherInputStream(data, cipher))
    {
        IOUtils.copy(cis, output);
    }
}
 
Example #2
Source File: GCMDataB.java    From InflatableDonkey with MIT License 7 votes vote down vote up
public static byte[] decrypt(byte[] key, byte[] data) {
    // TODO utilize GCMAES#decrypt method
    try {
        if (data.length < NONCE_LENGTH + TAG_LENGTH) {
            throw new IllegalArgumentException("data packet too short");
        }

        int cipherTextLength = data.length - NONCE_LENGTH - TAG_LENGTH;

        byte[] nonce = Arrays.copyOf(data, NONCE_LENGTH);

        GCMBlockCipher cipher = new GCMBlockCipher(new AESFastEngine());
        AEADParameters parameters = new AEADParameters(new KeyParameter(key), TAG_LENGTH * 8, nonce);
        cipher.init(false, parameters);

        byte[] out = new byte[cipher.getOutputSize(cipherTextLength + TAG_LENGTH)];

        int pos = cipher.processBytes(data, NONCE_LENGTH, data.length - NONCE_LENGTH, out, 0);
        pos += cipher.doFinal(out, pos);

        return Arrays.copyOf(out, pos);

    } catch (IllegalStateException | InvalidCipherTextException ex) {
        throw new IllegalArgumentException(ex);
    }
}
 
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: CredStashBouncyCastleCrypto.java    From jcredstash with Apache License 2.0 6 votes vote down vote up
private byte[] encryptOrDecrypt(byte[] key, byte[] contents, boolean forEncryption) {

        // Credstash uses standard AES
        BlockCipher engine = new AESFastEngine();

        // Credstash uses CTR mode
        StreamBlockCipher cipher = new SICBlockCipher(engine);

        cipher.init(forEncryption, new ParametersWithIV(new KeyParameter(key), INITIALIZATION_VECTOR));

        byte[] resultBytes = new byte[contents.length];
        int contentsOffset = 0;
        int resultOffset = 0;
        cipher.processBytes(contents, contentsOffset, contents.length, resultBytes, resultOffset);
        return resultBytes;
    }
 
Example #6
Source File: AESCBC.java    From InflatableDonkey with MIT License 6 votes vote down vote up
public static byte[] decryptAESCBC(byte[] key, byte[] iv, byte[] data) {
    // AES CBC PKCS7 decrypt
    try {
        CipherParameters cipherParameters = new ParametersWithIV(new KeyParameter(key), iv);
        PaddedBufferedBlockCipher cipher
                = new PaddedBufferedBlockCipher(new CBCBlockCipher(new AESFastEngine()), new PKCS7Padding());
        cipher.init(false, cipherParameters);

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

        int pos = cipher.processBytes(data, 0, data.length, buffer, 0);
        pos += cipher.doFinal(buffer, pos);

        return Arrays.copyOf(buffer, pos);

    } catch (DataLengthException | IllegalStateException | InvalidCipherTextException ex) {
        throw new IllegalArgumentException("decrypt failed", ex);
    }
}
 
Example #7
Source File: SAES256v01.java    From sfs with Apache License 2.0 6 votes vote down vote up
public SAES256v01(byte[] secretBytes, byte[] salt) {
    this.salt = salt.clone();
    secretBytes = secretBytes.clone();
    if (secretBytes.length != KEY_SIZE_BYTES) {
        secretBytes = Hashing.sha256().hashBytes(secretBytes).asBytes();
    }
    try {
        KeyParameter key = new KeyParameter(secretBytes);
        AEADParameters params = new AEADParameters(key, MAC_SIZE_BITS, this.salt);

        this.encryptor = new GCMBlockCipher(new AESFastEngine());
        this.encryptor.init(true, params);

        this.decryptor = new GCMBlockCipher(new AESFastEngine());
        this.decryptor.init(false, params);

    } catch (Exception e) {
        throw new RuntimeException("could not create cipher for AES256", e);
    } finally {
        Arrays.fill(secretBytes, (byte) 0);
    }
}
 
Example #8
Source File: CipherWriteStreamValidation.java    From sfs with Apache License 2.0 6 votes vote down vote up
public CipherWriteStreamValidation(byte[] secretBytes, byte[] salt) {
    this.salt = salt.clone();
    secretBytes = secretBytes.clone();
    if (secretBytes.length != KEY_SIZE_BYTES) {
        secretBytes = Hashing.sha256().hashBytes(secretBytes).asBytes();
    }
    try {
        KeyParameter key = new KeyParameter(secretBytes);
        AEADParameters params = new AEADParameters(key, MAC_SIZE_BITS, this.salt);

        this.encryptor = new GCMBlockCipher(new AESFastEngine());
        this.encryptor.init(true, params);

        this.decryptor = new GCMBlockCipher(new AESFastEngine());
        this.decryptor.init(false, params);

    } catch (Exception e) {
        throw new RuntimeException("could not create cipher for AES256", e);
    } finally {
        Arrays.fill(secretBytes, (byte) 0);
    }
}
 
Example #9
Source File: AESEncryptor.java    From archistar-smc with GNU Lesser General Public License v2.1 5 votes vote down vote up
@Override
public byte[] decrypt(byte[] data, byte[] randomKeyBytes)
        throws InvalidKeyException, InvalidAlgorithmParameterException, IOException, IllegalStateException, InvalidCipherTextException {

    PaddedBufferedBlockCipher cipher = new PaddedBufferedBlockCipher(new CBCBlockCipher(new AESFastEngine()));
    cipher.init(false, new ParametersWithIV(new KeyParameter(randomKeyBytes), randomIvBytes));
    return cipherData(cipher, data);
}
 
Example #10
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 #11
Source File: RFC6637Factory.java    From InflatableDonkey with MIT License 5 votes vote down vote up
public static synchronized RFC6637 secp256r1() {
    if (SECP256R1 == null) {
        SECP256R1 = create(
                "secp256r1",
                SHA256Digest::new,
                () -> new RFC3394WrapEngine(new AESFastEngine()),
                RFC6637Constants.ECDH,
                RFC6637Constants.AES_128,
                0x10,
                RFC6637Constants.SHA256);
    }

    return SECP256R1;
}
 
Example #12
Source File: RFC6637Factory.java    From InflatableDonkey with MIT License 5 votes vote down vote up
public static synchronized RFC6637 secp521r1() {
    if (SECP521R1 == null) {
        SECP521R1 = create(
                "secp521r1",
                SHA512Digest::new,
                () -> new RFC3394WrapEngine(new AESFastEngine()),
                RFC6637Constants.ECDH,
                RFC6637Constants.AES_256,
                0x20,
                RFC6637Constants.SHA512);
    }

    return SECP521R1;
}
 
Example #13
Source File: ECKey.java    From javasdk with GNU Lesser General Public License v3.0 5 votes vote down vote up
/**
 * Decrypt cipher by AES in SIC(also know as CTR) mode
 *
 * @param cipher -proper cipher
 * @return decrypted cipher, equal length to the cipher.
 * @deprecated should not use EC private scalar value as an AES key
 */
public byte[] decryptAES(byte[] cipher) {

    if (privKey == null) {
        throw new MissingPrivateKeyException();
    }
    if (!(privKey instanceof BCECPrivateKey)) {
        throw new UnsupportedOperationException("Cannot use the private key as an AES key");
    }


    AESFastEngine engine = new AESFastEngine();
    SICBlockCipher ctrEngine = new SICBlockCipher(engine);

    KeyParameter key = new KeyParameter(BigIntegers.asUnsignedByteArray(((BCECPrivateKey) privKey).getD()));
    ParametersWithIV params = new ParametersWithIV(key, new byte[16]);

    ctrEngine.init(false, params);

    int i = 0;
    byte[] out = new byte[cipher.length];
    while (i < cipher.length) {
        ctrEngine.processBlock(cipher, i, out, i);
        i += engine.getBlockSize();
        if (cipher.length - i < engine.getBlockSize())
            break;
    }

    // process left bytes
    if (cipher.length - i > 0) {
        byte[] tmpBlock = new byte[16];
        System.arraycopy(cipher, i, tmpBlock, 0, cipher.length - i);
        ctrEngine.processBlock(tmpBlock, 0, tmpBlock, 0);
        System.arraycopy(tmpBlock, 0, out, i, cipher.length - i);
    }

    return out;
}
 
Example #14
Source File: AESGCMEncryptor.java    From archistar-smc with GNU Lesser General Public License v2.1 5 votes vote down vote up
@Override
public byte[] encrypt(byte[] data, byte[] randomKeyBytes) throws IOException, InvalidKeyException,
        InvalidAlgorithmParameterException, InvalidCipherTextException {

    AEADBlockCipher cipher = new GCMBlockCipher(new AESFastEngine());
    cipher.init(true, new AEADParameters(new KeyParameter(randomKeyBytes), 128, randomIvBytes));
    return cipherData(cipher, data);
}
 
Example #15
Source File: RFC3394Wrap.java    From InflatableDonkey with MIT License 5 votes vote down vote up
public static Optional<byte[]> unwrapAES(byte[] keyEncryptionKey, byte[] wrappedKey) {
    try {
        RFC3394WrapEngine engine = new RFC3394WrapEngine(new AESFastEngine());
        engine.init(false, new KeyParameter(keyEncryptionKey));
        return Optional.of(engine.unwrap(wrappedKey, 0, wrappedKey.length));

    } catch (InvalidCipherTextException ex) {
        logger.debug("-- unwrap() - InvalidCipherTextException: {}", ex.getMessage());
        return Optional.empty();
    }
}
 
Example #16
Source File: AESGCM.java    From InflatableDonkey with MIT License 5 votes vote down vote up
/**
 * Returns decrypted data.
 *
 * @param key
 * @param nonce nonce/ IV
 * @param header
 * @param encryptedData
 * @param tag
 * @param optional optional AADBytes (post header)
 * @return decrypted data
 * @throws IllegalArgumentException on decryption exceptions
 * @throws NullPointerException on null arguments
 */
public static byte[] decrypt(
        byte[] key,
        byte[] nonce,
        byte[] header,
        byte[] encryptedData,
        byte[] tag,
        Optional<byte[]> optional) {

    try {
        GCMBlockCipher cipher = new GCMBlockCipher(new AESFastEngine());
        AEADParameters parameters = new AEADParameters(new KeyParameter(key), tag.length * 8, nonce, header);
        cipher.init(false, parameters);

        if (optional.isPresent()) {
            byte[] aadBytes = optional.get();
            cipher.processAADBytes(aadBytes, 0, aadBytes.length);
        }

        byte[] out = new byte[cipher.getOutputSize(encryptedData.length + tag.length)];

        int pos = cipher.processBytes(encryptedData, 0, encryptedData.length, out, 0);
        pos += cipher.processBytes(tag, 0, tag.length, out, pos);
        pos += cipher.doFinal(out, pos);

        return Arrays.copyOf(out, pos);

    } catch (IllegalStateException | InvalidCipherTextException | RuntimeCryptoException ex) {
        throw new IllegalStateException("GCM decrypt error", ex);
    }
}
 
Example #17
Source File: AESGCMEncryptor.java    From archistar-smc with GNU Lesser General Public License v2.1 5 votes vote down vote up
@Override
public byte[] decrypt(byte[] data, byte[] randomKey)
        throws InvalidKeyException, InvalidAlgorithmParameterException, IOException,
        IllegalStateException, InvalidCipherTextException {

    AEADBlockCipher cipher = new GCMBlockCipher(new AESFastEngine());
    cipher.init(false, new AEADParameters(new KeyParameter(randomKey), 128, randomIvBytes));
    return cipherData(cipher, data);
}
 
Example #18
Source File: CryptoPrimitives.java    From Clusion with GNU General Public License v3.0 5 votes vote down vote up
public static byte[] generateCmac(byte[] key, String msg) throws UnsupportedEncodingException {
	CMac cmac = new CMac(new AESFastEngine());
	byte[] data = msg.getBytes("UTF-8");
	byte[] output = new byte[cmac.getMacSize()];

	cmac.init(new KeyParameter(key));
	cmac.reset();
	cmac.update(data, 0, data.length);
	cmac.doFinal(output, 0);
	return output;
}
 
Example #19
Source File: AESEncryptor.java    From archistar-smc with GNU Lesser General Public License v2.1 5 votes vote down vote up
@Override
public byte[] encrypt(byte[] data, byte[] randomKeyBytes) throws IOException, InvalidKeyException,
        InvalidAlgorithmParameterException, InvalidCipherTextException {

    PaddedBufferedBlockCipher cipher = new PaddedBufferedBlockCipher(new CBCBlockCipher(new AESFastEngine()));
    cipher.init(true, new ParametersWithIV(new KeyParameter(randomKeyBytes), randomIvBytes));
    return cipherData(cipher, data);
}
 
Example #20
Source File: AESCipher.java    From itext2 with GNU Lesser General Public License v3.0 5 votes vote down vote up
/** Creates a new instance of AESCipher */
public AESCipher(boolean forEncryption, byte[] key, byte[] iv) {
    BlockCipher aes = new AESFastEngine();
    BlockCipher cbc = new CBCBlockCipher(aes);
    bp = new PaddedBufferedBlockCipher(cbc);
    KeyParameter kp = new KeyParameter(key);
    ParametersWithIV piv = new ParametersWithIV(kp, iv);
    bp.init(forEncryption, piv);
}
 
Example #21
Source File: EncryptionUtil.java    From DarkBot with BSD 2-Clause "Simplified" License 4 votes vote down vote up
public static BufferedBlockCipher createBlockCipher(SecretKey key, boolean out) {
	BufferedBlockCipher blockCipher = new BufferedBlockCipher(new CFBBlockCipher(new AESFastEngine(), 8));
	blockCipher.init(out, new ParametersWithIV(new KeyParameter(key.getEncoded()), key.getEncoded(), 0, 16));
	return blockCipher;
}
 
Example #22
Source File: XTSCore.java    From InflatableDonkey with MIT License 4 votes vote down vote up
XTSCore(XTSTweak tweak) {
    this(new AESFastEngine(), tweak);
}
 
Example #23
Source File: ConcatenatingAESEngine.java    From sambox with Apache License 2.0 4 votes vote down vote up
ConcatenatingAESEngine()
{
    super(new PaddedBufferedBlockCipher(new CBCBlockCipher(new AESFastEngine())));
    random = new SecureRandom();
}
 
Example #24
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 #25
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 #26
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 #27
Source File: XTSTweak.java    From InflatableDonkey with MIT License 4 votes vote down vote up
XTSTweak(LongFunction<byte[]> tweakFunction) {
    this(new AESFastEngine(), tweakFunction);
}
 
Example #28
Source File: RFC3394Wrap.java    From InflatableDonkey with MIT License 4 votes vote down vote up
public static byte[] wrapAES(byte[] keyEncryptionKey, byte[] unwrappedKey) {
    RFC3394WrapEngine engine = new RFC3394WrapEngine(new AESFastEngine());
    engine.init(true, new KeyParameter(keyEncryptionKey));
    return engine.wrap(unwrappedKey, 0, unwrappedKey.length);
}
 
Example #29
Source File: ChunkListDecrypter.java    From InflatableDonkey with MIT License 4 votes vote down vote up
CipherInputStream cipherInputStream(InputStream inputStream, byte[] key, byte[] checksum) {
    CFBBlockCipher cipher = new CFBBlockCipher(new AESFastEngine(), 128);
    KeyParameter keyParameter = new KeyParameter(key);
    cipher.init(false, keyParameter);
    return new CipherInputStream(inputStream, cipher);
}
 
Example #30
Source File: EncryptionUtil.java    From AIBot with GNU General Public License v3.0 4 votes vote down vote up
public static BufferedBlockCipher createBlockCipher(SecretKey key, boolean out) {
	BufferedBlockCipher blockCipher = new BufferedBlockCipher(new CFBBlockCipher(new AESFastEngine(), 8));
	blockCipher.init(out, new ParametersWithIV(new KeyParameter(key.getEncoded()), key.getEncoded(), 0, 16));
	return blockCipher;
}