SecretKeySpec skeySpec = new SecretKeySpec(y.getBytes(), "AES"); FileInputStream fis; FileOutputStream fos; CipherOutputStream cos; // File you are reading from fis = new FileInputStream("/tmp/a.txt"); // File output fos = new FileOutputStream("/tmp/b.txt"); // Here the file is encrypted. The cipher1 has to be created. // Key Length should be 128, 192 or 256 bit => i.e. 16 byte SecretKeySpec skeySpec = new SecretKeySpec("MyDifficultPassw".getBytes(), "AES"); Cipher cipher1 = Cipher.getInstance("AES"); cipher1.init(Cipher.ENCRYPT_MODE, skeySpec); cos = new CipherOutputStream(fos, cipher1); // Here you read from the file in fis and write to cos. byte[] b = new byte[8]; int i = fis.read(b); while (i != -1) { cos.write(b, 0, i); i = fis.read(b); } cos.flush();
static void encrypt() throws IOException, NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException { // Here you read the cleartext. FileInputStream fis = new FileInputStream("data/cleartext"); // This stream write the encrypted text. This stream will be wrapped by another stream. FileOutputStream fos = new FileOutputStream("data/encrypted"); // Length is 16 byte // Careful when taking user input!!! http://stackoverflow.com/a/3452620/1188357 SecretKeySpec sks = new SecretKeySpec("MyDifficultPassw".getBytes(), "AES"); // Create cipher Cipher cipher = Cipher.getInstance("AES"); cipher.init(Cipher.ENCRYPT_MODE, sks); // Wrap the output stream CipherOutputStream cos = new CipherOutputStream(fos, cipher); // Write bytes int b; byte[] d = new byte[8]; while((b = fis.read(d)) != -1) { cos.write(d, 0, b); } // Flush and close streams. cos.flush(); cos.close(); fis.close(); }
private static byte[] encryptBlocks(final byte[] data, final Cipher cipher, final int dataSize) throws IOException { final ByteArrayOutputStream bos = new ByteArrayOutputStream(data.length); final int count = (data.length / dataSize) + 1; int remaining = data.length; for (int i=0; i<count; i++) { final int offset = i*dataSize; final int length = Math.min(dataSize, remaining); final CipherOutputStream cos = new CipherOutputStream(bos, cipher); cos.write(data, offset, length); cos.flush(); cos.close(); remaining -= length; } return bos.toByteArray(); }
@Override public void flush() throws IOException { this.cipherStream.flush(); }
@Override /** * <p>Flushes this output stream by forcing any buffered output bytes that have already * been processed by the encapsulated cipher object to be written out.</p> * * <p>Any bytes buffered by the encapsulated cipher and waiting to be processed by it * will not be written out. For example, if the encapsulated cipher is a block cipher, * and the total number of bytes written using one of the write methods is less than * the cipher's block size, no bytes will be written out.</p> * * <p>This just proxies to the underlying CipherOutputStream.</p> */ public void flush() throws IOException { cipherOutputStream.flush(); }
@Override public void close() throws IOException { super.flush(); try { byte[] bytes = cipher.doFinal(); outputStream.write(bytes); outputStream.close(); } catch (IllegalBlockSizeException e) { throw new IOException(e); } catch (BadPaddingException e) { throw new IOException(e); } } };
public static void encryptFile(File src, File dst) throws Exception { if (!dst.getParentFile().exists()) dst.getParentFile().mkdirs(); Cipher encrypt = Cipher.getInstance("AES/CBC/PKCS5Padding"); encrypt.init(Cipher.ENCRYPT_MODE, key, spec); // opening streams FileOutputStream fos = new FileOutputStream(dst); FileInputStream fis = new FileInputStream(src); CipherOutputStream cout = new CipherOutputStream(fos, encrypt); IOUtils.copy(fis, cout); cout.flush(); cout.close(); fis.close(); }
public static void encryptFile(File src, File dst, IvParameterSpec ivspec) throws Exception { if (!dst.getParentFile().exists()) dst.getParentFile().mkdirs(); Cipher encrypt = Cipher.getInstance("AES/CBC/PKCS5Padding"); encrypt.init(Cipher.ENCRYPT_MODE, key, ivspec); // opening streams FileOutputStream fos = new FileOutputStream(dst); FileInputStream fis = new FileInputStream(src); CipherOutputStream cout = new CipherOutputStream(fos, encrypt); IOUtils.copy(fis, cout); cout.flush(); cout.close(); fis.close(); }
FileInputStream fis; FileOutputStream fos; CipherOutputStream cos; // File you are reading from fis = new FileInputStream("/tmp/a.txt"); // File output fos = new FileOutputStream("/tmp/b.txt"); // Here the file is encrypted. The cipher1 has to be created. // Key Length should be 128, 192 or 256 bit => i.e. 16 byte SecretKeySpec skeySpec = new SecretKeySpec("MyDifficultPassw".getBytes(), "AES"); Cipher cipher1 = Cipher.getInstance("AES"); cipher1.init(Cipher.ENCRYPT_MODE, skeySpec); cos = new CipherOutputStream(fos, cipher1); // Here you read from the file in fis and write to cos. byte[] b = new byte[8]; int i = fis.read(b); while (i != -1) { cos.write(b, 0, i); i = fis.read(b); } cos.flush();
byte[] encrypt(byte[] data) { if (encryptCipher == null) { return data; } try { ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); CipherOutputStream cipherOutputStream = new CipherOutputStream(outputStream, encryptCipher); cipherOutputStream.write(data); cipherOutputStream.flush(); cipherOutputStream.close(); byte[] encryptedBytes = outputStream.toByteArray(); return encryptedBytes; } catch (IOException e) { LOG.debug("encrypt failed", e); throw new RuntimeException(e); } }
byte[] encrypt(byte[] data) { if (encryptCipher == null) { return data; } try { ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); CipherOutputStream cipherOutputStream = new CipherOutputStream(outputStream, encryptCipher); cipherOutputStream.write(data); cipherOutputStream.flush(); cipherOutputStream.close(); byte[] encryptedBytes = outputStream.toByteArray(); return encryptedBytes; } catch (IOException e) { LOG.debug("encrypt failed", e); throw new RuntimeException(e); } }
static void encrypt() throws IOException, NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException { // Here you read the cleartext. FileInputStream fis = new FileInputStream("data/cleartext"); // This stream write the encrypted text. This stream will be wrapped by another stream. FileOutputStream fos = new FileOutputStream("data/encrypted"); // Length is 16 byte SecretKeySpec sks = new SecretKeySpec("MyDifficultPassw".getBytes(), "AES"); // Create cipher Cipher cipher = Cipher.getInstance("AES"); cipher.init(Cipher.ENCRYPT_MODE, sks); // Wrap the output stream CipherOutputStream cos = new CipherOutputStream(fos, cipher); // Write bytes int b; byte[] d = new byte[8]; while((b = fis.read(d)) != -1) { cos.write(d, 0, b); } // Flush and close streams. cos.flush(); cos.close(); fis.close(); }
public void encrypt() throws IOException, NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException { // Here you read the cleartext. FileInputStream fis = new FileInputStream("data/cleartext"); // This stream write the encrypted text. This stream will be wrapped by // another stream. FileOutputStream fos = new FileOutputStream("data/encrypted"); // Length is 16 byte SecretKeySpec sks = new SecretKeySpec("yourkey".getBytes(), "AES"); // Create cipher Cipher cipher = Cipher.getInstance("AES/CBC"); cipher.init(Cipher.ENCRYPT_MODE, sks); // Wrap the output stream CipherOutputStream cos = new CipherOutputStream(fos, cipher); // Write bytes int b; byte[] d = new byte[8]; while ((b = fis.read(d)) != -1) { cos.write(d, 0, b); } // Flush and close streams. cos.flush(); cos.close(); fis.close(); }
static void encrypt() throws IOException, NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException { // Here you read the cleartext. FileInputStream fis = new FileInputStream("SampleFolder/yourfilename"); // This stream write the encrypted text. This stream will be wrapped by another stream. FileOutputStream fos = new FileOutputStream("SampleFolder/yourencryptedfilename"); // Length is 16 byte // Careful when taking user input!!! http://stackoverflow.com/a/3452620/1188357 SecretKeySpec sks = new SecretKeySpec("MyDifficultPassw".getBytes(), "AES"); // Create cipher Cipher cipher = Cipher.getInstance("AES"); cipher.init(Cipher.ENCRYPT_MODE, sks); // Wrap the output stream CipherOutputStream cos = new CipherOutputStream(fos, cipher); // Write bytes int b; byte[] d = new byte[8]; while((b = fis.read(d)) != -1) { cos.write(d, 0, b); } // Flush and close streams. cos.flush(); cos.close(); fis.close(); }
/** * Encrypt a value with a key and initial vector * * @param value * the String value to encrypt * @param iv * the initial vector. Must be a random 128 bit value and the * same one used in decryption * @param key * the key for encryption * * @return the encrypted bytes */ public byte[] encrypt(String value, byte[] iv, SecretKey key) throws InvalidKeyException, InvalidAlgorithmParameterException, IOException { byte[] encryptedBytes = null; IvParameterSpec ivspec = new IvParameterSpec(iv); encryptCipher.init(Cipher.ENCRYPT_MODE, key, ivspec); ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); CipherOutputStream cipherOutputStream = new CipherOutputStream(outputStream, encryptCipher); cipherOutputStream.write(value.getBytes(StandardCharsets.UTF_8)); cipherOutputStream.flush(); cipherOutputStream.close(); encryptedBytes = outputStream.toByteArray(); return encryptedBytes; }
/* Derive the key, given password and salt. */ SecretKeyFactory factory = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA1"); KeySpec spec = new PBEKeySpec(password, salt, 65536, 256); SecretKey tmp = factory.generateSecret(spec); SecretKey secret = new SecretKeySpec(tmp.getEncoded(), "AES"); /* Encrypt the message. */ Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding"); cipher.init(Cipher.ENCRYPT_MODE, secret); AlgorithmParameters params = cipher.getParameters(); byte[] iv = params.getParameterSpec(IvParameterSpec.class).getIV(); try (OutputStream fos = Files.newOutputStream(output, StandardOpenOption.CREATE_NEW); CipherOutputStream os = new CipherOutputStream(fos, cipher); InputStream is = Files.newInputStream(input)) { byte[] buffer = new byte[4096]; while (true) { int n = is.read(buffer); if (n < 0) break; os.write(buffer, 0, n); } os.flush(); }
/** * This method encrypts a byte stream using a shared key. * * @param sharedKey The shared key used for the encryption. * @param input The byte stream to be encrypted. * @param output The encrypted output stream. * @throws java.io.IOException Unable to encrypt the stream. */ public final void encryptStream(SecretKey sharedKey, InputStream input, OutputStream output) throws IOException { logger.entry(); CipherOutputStream cipherOutput = null; byte[] buffer = new byte[2048]; try { logger.debug("Creating a special output stream to do the work..."); cipherOutput = encryptionOutputStream(sharedKey, output); logger.debug("Reading from the input and writing to the encrypting output stream..."); // Can't use IOUtils.copy(input, cipherOutput) here because need to purge buffer later... int bytesRead; while ((bytesRead = input.read(buffer)) != -1) { cipherOutput.write(buffer, 0, bytesRead); } cipherOutput.flush(); } finally { logger.debug("Purging any plaintext hanging around in memory..."); Arrays.fill(buffer, (byte) 0); if (cipherOutput != null) cipherOutput.close(); } logger.exit(); }
public void marshal(Exchange exchange, Object graph, OutputStream outputStream) throws Exception { byte[] iv = getInitializationVector(exchange); Key key = getKey(exchange); InputStream plaintextStream = ExchangeHelper.convertToMandatoryType(exchange, InputStream.class, graph); HMACAccumulator hmac = getMessageAuthenticationCode(key); if (plaintextStream != null) { inlineInitVector(outputStream, iv); byte[] buffer = new byte[bufferSize]; int read; CipherOutputStream cipherStream = null; try { cipherStream = new CipherOutputStream(outputStream, initializeCipher(ENCRYPT_MODE, key, iv)); while ((read = plaintextStream.read(buffer)) > 0) { cipherStream.write(buffer, 0, read); cipherStream.flush(); hmac.encryptUpdate(buffer, read); } // only write if there is data to write (IBM JDK throws exception if no data) byte[] mac = hmac.getCalculatedMac(); if (mac != null && mac.length > 0) { cipherStream.write(mac); } } finally { IOHelper.close(cipherStream, "cipher", LOG); IOHelper.close(plaintextStream, "plaintext", LOG); } } }