org.spongycastle.crypto.engines.AESFastEngine Java Examples

The following examples show how to use org.spongycastle.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: KeyCrypterScrypt.java    From bcm-android with GNU General Public License v3.0 6 votes vote down vote up
/**
 * Decrypt bytes previously encrypted with this class.
 *
 * @param dataToDecrypt The data to decrypt
 * @param aesKey        The AES key to use for decryption
 * @return The decrypted bytes
 * @throws KeyCrypterException if bytes could not be decrypted
 */
@Override
public byte[] decrypt(EncryptedData dataToDecrypt, KeyParameter aesKey) throws KeyCrypterException {
    checkNotNull(dataToDecrypt);
    checkNotNull(aesKey);

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

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

        byte[] cipherBytes = dataToDecrypt.encryptedBytes;
        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 KeyCrypterException("Could not decrypt bytes", e);
    }
}
 
Example #2
Source File: SensitiveDataPreApi23.java    From android-java-connect-rest-sample with MIT License 6 votes vote down vote up
protected byte[] decrypt(byte[] data) {

        try {
            SecretKey key = loadKey();

            byte[] ivBytes = new byte[16];                                                                  // 16 bytes is the IV size for AES256
            System.arraycopy(data, 0, ivBytes, 0, ivBytes.length);                                          // Get IV from data
            byte[] dataWithoutIV = new byte[data.length - ivBytes.length];                                  // Remove the room made for the IV
            System.arraycopy(data, ivBytes.length, dataWithoutIV, 0, dataWithoutIV.length);                 // Then the encrypted data

            PaddedBufferedBlockCipher cipher = new PaddedBufferedBlockCipher(new CBCBlockCipher(new AESFastEngine()));
            cipher.init(false, new ParametersWithIV(new KeyParameter(key.getEncoded()), ivBytes));

            return cipherData(cipher, dataWithoutIV);
        }
        catch(InvalidCipherTextException e) {
            Log.e(TAG, "Can't decrypt data", e);
        }
        return null;
    }
 
Example #3
Source File: SensitiveDataPreApi23.java    From android-java-connect-rest-sample with MIT License 6 votes vote down vote up
protected byte[] encrypt(byte[] data) {
    // 16 bytes is the IV size for AES256
    try {
        SecretKey key = loadKey();

        // Random IV
        SecureRandom rng = new SecureRandom();
        byte[] ivBytes = new byte[16];                                                                  // 16 bytes is the IV size for AES256
        rng.nextBytes(ivBytes);

        PaddedBufferedBlockCipher cipher = new PaddedBufferedBlockCipher(new CBCBlockCipher(new AESFastEngine()));
        cipher.init(true, new ParametersWithIV(new KeyParameter(key.getEncoded()), ivBytes));

        byte[] encryptedData = cipherData(cipher, data);
        byte[] encryptedDataWithIV = new byte[encryptedData.length + ivBytes.length];                   // Make room for IV
        System.arraycopy(ivBytes, 0, encryptedDataWithIV, 0, ivBytes.length);                           // Add IV
        System.arraycopy(encryptedData, 0, encryptedDataWithIV, ivBytes.length, encryptedData.length);  // Then the encrypted data
        return encryptedDataWithIV;
    }
    catch(InvalidCipherTextException e) {
        Log.e(TAG, "Can't encrypt data", e);
    }
    return null;
}
 
Example #4
Source File: KeyCrypterScrypt.java    From GreenBits with GNU General Public License v3.0 6 votes vote down vote up
/**
 * Decrypt bytes previously encrypted with this class.
 *
 * @param dataToDecrypt    The data to decrypt
 * @param aesKey           The AES key to use for decryption
 * @return                 The decrypted bytes
 * @throws                 KeyCrypterException if bytes could not be decrypted
 */
@Override
public byte[] decrypt(EncryptedData dataToDecrypt, KeyParameter aesKey) throws KeyCrypterException {
    checkNotNull(dataToDecrypt);
    checkNotNull(aesKey);

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

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

        byte[] cipherBytes = dataToDecrypt.encryptedBytes;
        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 KeyCrypterException("Could not decrypt bytes", e);
    }
}
 
Example #5
Source File: KeyCrypterScrypt.java    From GreenBits with GNU General Public License v3.0 6 votes vote down vote up
/**
 * Password based encryption using AES - CBC 256 bits.
 */
@Override
public EncryptedData encrypt(byte[] plainBytes, KeyParameter aesKey) throws KeyCrypterException {
    checkNotNull(plainBytes);
    checkNotNull(aesKey);

    try {
        // Generate iv - each encryption call has a different iv.
        byte[] iv = new byte[BLOCK_LENGTH];
        secureRandom.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 KeyCrypterException("Could not encrypt bytes.", e);
    }
}
 
Example #6
Source File: aes.java    From bitshares_wallet with MIT License 6 votes vote down vote up
public static ByteBuffer decrypt(byte[] key, byte[] iv, byte[] cipertext) {
    try
    {
        PaddedBufferedBlockCipher cipher = new PaddedBufferedBlockCipher(new CBCBlockCipher(new AESFastEngine()));
        cipher.init(false, new ParametersWithIV(new KeyParameter(key), iv));
        byte[] clear = new byte[cipher.getOutputSize(cipertext.length)];
        int len = cipher.processBytes(cipertext, 0, cipertext.length, clear,0);
        len += cipher.doFinal(clear, len);
        ByteBuffer byteBuffer = ByteBuffer.allocate(len);
        byteBuffer.put(clear, 0, len);
        return byteBuffer;
    }
    catch(Exception e)
    {
        e.printStackTrace();
    }
    return null;

}
 
Example #7
Source File: aes.java    From bitshares_wallet with MIT License 6 votes vote down vote up
public static ByteBuffer encrypt(byte[] key, byte[] iv, byte[] plaintext) {
    assert (key.length == 32 && iv.length == 16);
    try
    {
        PaddedBufferedBlockCipher cipher = new PaddedBufferedBlockCipher(new CBCBlockCipher(new AESFastEngine()));

        cipher.init(true, new ParametersWithIV(new KeyParameter(key), iv));
        byte[] outBuf   = new byte[cipher.getOutputSize(plaintext.length)];
        int processed = cipher.processBytes(plaintext, 0, plaintext.length, outBuf, 0);
        processed += cipher.doFinal(outBuf, processed);

        ByteBuffer byteBuffer = ByteBuffer.allocate(processed);
        byteBuffer.put(outBuf, 0, processed);
        return byteBuffer;
    }
    catch(Exception e)
    {
        e.printStackTrace();
    }
    return null;
}
 
Example #8
Source File: AESEncrypt.java    From nuls with MIT License 6 votes vote down vote up
public static byte[] decrypt(EncryptedData dataToDecrypt, KeyParameter aesKey) throws CryptoException {
    Util.checkNotNull(dataToDecrypt);
    Util.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 #9
Source File: AESEncrypt.java    From nuls with MIT License 6 votes vote down vote up
public static EncryptedData encrypt(byte[] plainBytes, byte[] iv, KeyParameter aesKey) throws RuntimeException {
    Util.checkNotNull(plainBytes);
    Util.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 #10
Source File: ECIESCoder.java    From wkcwallet-java with Apache License 2.0 6 votes vote down vote up
private static EthereumIESEngine makeIESEngine(boolean isEncrypt, ECPoint pub, BigInteger prv, byte[] IV) {
    AESFastEngine aesFastEngine = new AESFastEngine();

    EthereumIESEngine iesEngine = new EthereumIESEngine(
            new ECDHBasicAgreement(),
            new ConcatKDFBytesGenerator(new SHA256Digest()),
            new HMac(new SHA256Digest()),
            new SHA256Digest(),
            new BufferedBlockCipher(new SICBlockCipher(aesFastEngine)));


    byte[]         d = new byte[] {};
    byte[]         e = new byte[] {};

    IESParameters p = new IESWithCipherParameters(d, e, KEY_SIZE, KEY_SIZE);
    ParametersWithIV parametersWithIV = new ParametersWithIV(p, IV);

    iesEngine.init(isEncrypt, new ECPrivateKeyParameters(prv, CURVE), new ECPublicKeyParameters(pub, CURVE), parametersWithIV);
    return iesEngine;
}
 
Example #11
Source File: ECIESCoder.java    From wkcwallet-java with Apache License 2.0 6 votes vote down vote up
public static byte[] decrypt(ECPoint ephem, BigInteger prv, byte[] IV, byte[] cipher, byte[] macData) throws InvalidCipherTextException {
    AESFastEngine aesFastEngine = new AESFastEngine();

    EthereumIESEngine iesEngine = new EthereumIESEngine(
            new ECDHBasicAgreement(),
            new ConcatKDFBytesGenerator(new SHA256Digest()),
            new HMac(new SHA256Digest()),
            new SHA256Digest(),
            new BufferedBlockCipher(new SICBlockCipher(aesFastEngine)));


    byte[]         d = new byte[] {};
    byte[]         e = new byte[] {};

    IESParameters p = new IESWithCipherParameters(d, e, KEY_SIZE, KEY_SIZE);
    ParametersWithIV parametersWithIV =
            new ParametersWithIV(p, IV);

    iesEngine.init(false, new ECPrivateKeyParameters(prv, CURVE), new ECPublicKeyParameters(ephem, CURVE), parametersWithIV);

    return iesEngine.processBlock(cipher, 0, cipher.length, macData);
}
 
Example #12
Source File: KeyCrypterScrypt.java    From green_android with GNU General Public License v3.0 6 votes vote down vote up
/**
 * Decrypt bytes previously encrypted with this class.
 *
 * @param dataToDecrypt    The data to decrypt
 * @param aesKey           The AES key to use for decryption
 * @return                 The decrypted bytes
 * @throws                 KeyCrypterException if bytes could not be decrypted
 */
@Override
public byte[] decrypt(EncryptedData dataToDecrypt, KeyParameter aesKey) throws KeyCrypterException {
    checkNotNull(dataToDecrypt);
    checkNotNull(aesKey);

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

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

        byte[] cipherBytes = dataToDecrypt.encryptedBytes;
        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 KeyCrypterException("Could not decrypt bytes", e);
    }
}
 
Example #13
Source File: aes.java    From guarda-android-wallets with GNU General Public License v3.0 6 votes vote down vote up
public static ByteBuffer decrypt(byte[] key, byte[] iv, byte[] cipertext) {
    try
    {
        PaddedBufferedBlockCipher cipher = new PaddedBufferedBlockCipher(new CBCBlockCipher(new AESFastEngine()));
        cipher.init(false, new ParametersWithIV(new KeyParameter(key), iv));
        byte[] clear = new byte[cipher.getOutputSize(cipertext.length)];
        int len = cipher.processBytes(cipertext, 0, cipertext.length, clear,0);
        len += cipher.doFinal(clear, len);
        ByteBuffer byteBuffer = ByteBuffer.allocate(len);
        byteBuffer.put(clear, 0, len);
        return byteBuffer;
    }
    catch(Exception e)
    {
        e.printStackTrace();
    }
    return null;

}
 
Example #14
Source File: aes.java    From guarda-android-wallets with GNU General Public License v3.0 6 votes vote down vote up
public static ByteBuffer encrypt(byte[] key, byte[] iv, byte[] plaintext) {
    assert (key.length == 32 && iv.length == 16);
    try
    {
        PaddedBufferedBlockCipher cipher = new PaddedBufferedBlockCipher(new CBCBlockCipher(new AESFastEngine()));

        cipher.init(true, new ParametersWithIV(new KeyParameter(key), iv));
        byte[] outBuf   = new byte[cipher.getOutputSize(plaintext.length)];
        int processed = cipher.processBytes(plaintext, 0, plaintext.length, outBuf, 0);
        processed += cipher.doFinal(outBuf, processed);

        ByteBuffer byteBuffer = ByteBuffer.allocate(processed);
        byteBuffer.put(outBuf, 0, processed);
        return byteBuffer;
    }
    catch(Exception e)
    {
        e.printStackTrace();
    }
    return null;
}
 
Example #15
Source File: KeyCrypterScrypt.java    From bcm-android with GNU General Public License v3.0 6 votes vote down vote up
/**
 * Password based encryption using AES - CBC 256 bits.
 */
@Override
public EncryptedData encrypt(byte[] plainBytes, KeyParameter aesKey) throws KeyCrypterException {
    checkNotNull(plainBytes);
    checkNotNull(aesKey);

    try {
        // Generate iv - each encryption call has a different iv.
        byte[] iv = new byte[BLOCK_LENGTH];
        secureRandom.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 KeyCrypterException("Could not encrypt bytes.", e);
    }
}
 
Example #16
Source File: aes.java    From AndroidWallet with GNU General Public License v3.0 6 votes vote down vote up
public static ByteBuffer decrypt(byte[] key, byte[] iv, byte[] cipertext) {
    try {
        PaddedBufferedBlockCipher cipher = new PaddedBufferedBlockCipher(new CBCBlockCipher(new AESFastEngine()));
        cipher.init(false, new ParametersWithIV(new KeyParameter(key), iv));
        byte[] clear = new byte[cipher.getOutputSize(cipertext.length)];
        int len = cipher.processBytes(cipertext, 0, cipertext.length, clear, 0);
        len += cipher.doFinal(clear, len);
        ByteBuffer byteBuffer = ByteBuffer.allocate(len);
        byteBuffer.put(clear, 0, len);
        return byteBuffer;
    } catch (Exception e) {
        e.printStackTrace();
    }
    return null;

}
 
Example #17
Source File: aes.java    From AndroidWallet with GNU General Public License v3.0 6 votes vote down vote up
public static ByteBuffer encrypt(byte[] key, byte[] iv, byte[] plaintext) {
    assert (key.length == 64 && iv.length == 32);
    try {
        PaddedBufferedBlockCipher cipher = new PaddedBufferedBlockCipher(new CBCBlockCipher(new AESFastEngine()));

        cipher.init(true, new ParametersWithIV(new KeyParameter(key), iv));
        byte[] outBuf = new byte[cipher.getOutputSize(plaintext.length)];
        int processed = cipher.processBytes(plaintext, 0, plaintext.length, outBuf, 0);
        processed += cipher.doFinal(outBuf, processed);

        ByteBuffer byteBuffer = ByteBuffer.allocate(processed);
        byteBuffer.put(outBuf, 0, processed);
        return byteBuffer;
    } catch (Exception e) {
        e.printStackTrace();
    }
    return null;
}
 
Example #18
Source File: ProfileCipher.java    From bcm-android with GNU General Public License v3.0 6 votes vote down vote up
public byte[] encryptName(byte[] input, int paddedLength) {
    try {
        byte[] inputPadded = new byte[paddedLength];

        if (input.length > inputPadded.length) {
            throw new IllegalArgumentException("Input is too long: " + new String(input));
        }

        System.arraycopy(input, 0, inputPadded, 0, input.length);

        byte[] nonce = Util.getSecretBytes(12);

        GCMBlockCipher cipher = new GCMBlockCipher(new AESFastEngine());
        cipher.init(true, new AEADParameters(new KeyParameter(key), 128, nonce));

        byte[] ciphertext = new byte[cipher.getUpdateOutputSize(inputPadded.length)];
        cipher.processBytes(inputPadded, 0, inputPadded.length, ciphertext, 0);

        byte[] tag = new byte[cipher.getOutputSize(0)];
        cipher.doFinal(tag, 0);

        return ByteUtil.combine(nonce, ciphertext, tag);
    } catch (InvalidCipherTextException e) {
        throw new AssertionError(e);
    }
}
 
Example #19
Source File: KeyCrypterScrypt.java    From green_android with GNU General Public License v3.0 6 votes vote down vote up
/**
 * Password based encryption using AES - CBC 256 bits.
 */
@Override
public EncryptedData encrypt(byte[] plainBytes, KeyParameter aesKey) throws KeyCrypterException {
    checkNotNull(plainBytes);
    checkNotNull(aesKey);

    try {
        // Generate iv - each encryption call has a different iv.
        byte[] iv = new byte[BLOCK_LENGTH];
        secureRandom.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 KeyCrypterException("Could not encrypt bytes.", e);
    }
}
 
Example #20
Source File: CryptoPrimitivesAndroid.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 #21
Source File: KeyCrypterScrypt.java    From bitherj with Apache License 2.0 5 votes vote down vote up
/**
 * Decrypt bytes previously encrypted with this class.
 *
 * @param privateKeyToDecode The private key to decrypt
 * @param aesKey             The AES key to use for decryption
 * @return The decrypted bytes
 * @throws KeyCrypterException if bytes could not be decoded to a valid key
 */
@Override
public byte[] decrypt(EncryptedPrivateKey privateKeyToDecode, KeyParameter aesKey) throws KeyCrypterException {
    checkNotNull(privateKeyToDecode);
    checkNotNull(aesKey);

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

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

        byte[] cipherBytes = privateKeyToDecode.getEncryptedBytes();
        int minimumSize = cipher.getOutputSize(cipherBytes.length);
        byte[] outputBuffer = new byte[minimumSize];
        int length1 = cipher.processBytes(cipherBytes, 0, cipherBytes.length, outputBuffer, 0);
        int length2 = cipher.doFinal(outputBuffer, length1);
        int actualLength = length1 + length2;

        byte[] decryptedBytes = new byte[actualLength];
        System.arraycopy(outputBuffer, 0, decryptedBytes, 0, actualLength);

        Utils.wipeBytes(outputBuffer);

        return decryptedBytes;
    } catch (Exception e) {
        throw new KeyCrypterException("Could not decrypt bytes", e);
    }
}
 
Example #22
Source File: ProfileCipherInputStream.java    From bcm-android with GNU General Public License v3.0 5 votes vote down vote up
public ProfileCipherInputStream(InputStream in, byte[] key) throws IOException {
  super(in);
  this.cipher = new GCMBlockCipher(new AESFastEngine());

  byte[] nonce = Util.readFullLength(in, 12);
  this.cipher.init(false, new AEADParameters(new KeyParameter(key), 128, nonce));
}
 
Example #23
Source File: ProfileCipher.java    From bcm-android with GNU General Public License v3.0 5 votes vote down vote up
public byte[] decryptName(byte[] input) throws InvalidCiphertextException {
    try {
        if (input.length < 12 + 16 + 1) {
            throw new InvalidCiphertextException("Too short: " + input.length);
        }

        byte[] nonce = new byte[12];
        System.arraycopy(input, 0, nonce, 0, nonce.length);

        GCMBlockCipher cipher = new GCMBlockCipher(new AESFastEngine());
        cipher.init(false, new AEADParameters(new KeyParameter(key), 128, nonce));

        byte[] paddedPlaintextOne = new byte[cipher.getUpdateOutputSize(input.length - 12)];
        cipher.processBytes(input, 12, input.length - 12, paddedPlaintextOne, 0);

        byte[] paddedPlaintextTwo = new byte[cipher.getOutputSize(0)];
        cipher.doFinal(paddedPlaintextTwo, 0);

        byte[] paddedPlaintext = ByteUtil.combine(paddedPlaintextOne, paddedPlaintextTwo);
        int plaintextLength = 0;

        for (int i = paddedPlaintext.length - 1; i >= 0; i--) {
            if (paddedPlaintext[i] != (byte) 0x00) {
                plaintextLength = i + 1;
                break;
            }
        }

        byte[] plaintext = new byte[plaintextLength];
        System.arraycopy(paddedPlaintext, 0, plaintext, 0, plaintextLength);

        return plaintext;
    } catch (InvalidCipherTextException e) {
        throw new InvalidCiphertextException(e);
    }
}
 
Example #24
Source File: Encryption.java    From KeePassJava2 with Apache License 2.0 5 votes vote down vote up
/**
 * Create an encrypted output stream from an unencrypted output stream
 */
public static OutputStream getEncryptedOutputStream (OutputStream decryptedOutputStream, byte[] keyData, byte[] ivData) {
    final ParametersWithIV keyAndIV = new ParametersWithIV(new KeyParameter(keyData), ivData);
    PaddedBufferedBlockCipher pbbc = new PaddedBufferedBlockCipher(new CBCBlockCipher(new AESFastEngine()));
    pbbc.init(true, keyAndIV);
    return new CipherOutputStream(decryptedOutputStream, pbbc);
}
 
Example #25
Source File: Encryption.java    From KeePassJava2 with Apache License 2.0 5 votes vote down vote up
/**
 * Create a decrypted input stream from an encrypted one
 */
public static InputStream getDecryptedInputStream (InputStream encryptedInputStream, byte[] keyData, byte[] ivData) {
    final ParametersWithIV keyAndIV = new ParametersWithIV(new KeyParameter(keyData), ivData);
    PaddedBufferedBlockCipher pbbc = new PaddedBufferedBlockCipher(new CBCBlockCipher(new AESFastEngine()));
    pbbc.init(false, keyAndIV);
    return new CipherInputStream(encryptedInputStream, pbbc);
}
 
Example #26
Source File: ProfileCipherOutputStream.java    From bcm-android with GNU General Public License v3.0 5 votes vote down vote up
public ProfileCipherOutputStream(OutputStream out, byte[] key) throws IOException {
  super(out);
  this.cipher = new GCMBlockCipher(new AESFastEngine());

  byte[] nonce  = generateNonce();
  this.cipher.init(true, new AEADParameters(new KeyParameter(key), 128, nonce));

  super.write(nonce, 0, nonce.length);
}
 
Example #27
Source File: ECKeySecp256k1.java    From aion with MIT License 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 #28
Source File: ECKey.java    From tron-wallet-android with Apache License 2.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 #29
Source File: ECKey.java    From wkcwallet-java with Apache License 2.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 #30
Source File: Crypto.java    From KeePassJava2 with Apache License 2.0 2 votes vote down vote up
/**
 * Get a cipher
 *
 * @param mode encryption or decryption
 * @param iv   a 16 byte iv
 * @return an initialised Cipher
 */
PaddedBufferedBlockCipher getCipher(CMode mode, byte[] iv) {
    PaddedBufferedBlockCipher result = new PaddedBufferedBlockCipher(new CBCBlockCipher(new AESFastEngine()));
    result.init(mode.getEncrypt(), new ParametersWithIV(new KeyParameter(getKey()), iv));
    return result;
}