List of usage examples for javax.crypto CipherOutputStream write
public void write(byte b[], int off, int len) throws IOException
len
bytes from the specified byte array starting at offset off
to this output stream. From source file:com.microsoft.azure.storage.core.Utility.java
/** * Encrypts an input stream up to a given length. * Exits early if the encrypted data is longer than the abandon length. * //from www .j a v a 2s. c om * @param sourceStream * A <code>InputStream</code> object that represents the stream to measure. * @param targetStream * A <code>ByteArrayOutputStream</code> object that represents the stream to write the encrypted data. * @param cipher * The <code>Cipher</code> to use to encrypt the data. * @param writeLength * The number of bytes to read and encrypt from the sourceStream. * @param abandonLength * The number of bytes to read before the analysis is abandoned. Set this value to <code>-1</code> to * force the entire stream to be read. This parameter is provided to support upload thresholds. * @return * The size of the encrypted stream, or -1 if the encrypted stream would be over the abandonLength. * @throws IOException * If an I/O error occurs. */ public static long encryptStreamIfUnderThreshold(final InputStream sourceStream, final ByteArrayOutputStream targetStream, Cipher cipher, long writeLength, long abandonLength) throws IOException { if (abandonLength < 0) { abandonLength = Long.MAX_VALUE; } if (!sourceStream.markSupported()) { throw new IllegalArgumentException(SR.INPUT_STREAM_SHOULD_BE_MARKABLE); } sourceStream.mark(Constants.MAX_MARK_LENGTH); if (writeLength < 0) { writeLength = Long.MAX_VALUE; } CipherOutputStream encryptStream = new CipherOutputStream(targetStream, cipher); int count = -1; long totalEncryptedLength = targetStream.size(); final byte[] retrievedBuff = new byte[Constants.BUFFER_COPY_LENGTH]; int nextCopy = (int) Math.min(retrievedBuff.length, writeLength - totalEncryptedLength); count = sourceStream.read(retrievedBuff, 0, nextCopy); while (nextCopy > 0 && count != -1) { // Note: We are flushing the CryptoStream on every write here. This way, we don't end up encrypting more data than we intend here, if // we go over the abandonLength. encryptStream.write(retrievedBuff, 0, count); encryptStream.flush(); totalEncryptedLength = targetStream.size(); if (totalEncryptedLength > abandonLength) { // Abandon operation break; } nextCopy = (int) Math.min(retrievedBuff.length, writeLength - totalEncryptedLength); count = sourceStream.read(retrievedBuff, 0, nextCopy); } sourceStream.reset(); sourceStream.mark(Constants.MAX_MARK_LENGTH); encryptStream.close(); totalEncryptedLength = targetStream.size(); if (totalEncryptedLength > abandonLength) { totalEncryptedLength = -1; } return totalEncryptedLength; }
From source file:com.pari.nm.utils.backup.BackupRestore.java
private void encrypt(File backupZipFile, File encrBackupZipFile) throws Exception { try {/* w ww .j a v a 2 s . c o m*/ File f = new File("/etc/secondTime"); if (!f.exists()) { f.createNewFile(); } } catch (Exception ee) { } FileOutputStream fout = new FileOutputStream(encrBackupZipFile); Cipher cipher = Cipher.getInstance("DESEDE"); cipher.init(Cipher.ENCRYPT_MODE, getDefaultKey()); CipherOutputStream cout = new CipherOutputStream(fout, cipher); byte[] buffer = new byte[8192]; FileInputStream fin = new FileInputStream(backupZipFile); try { int read = fin.read(buffer); while (read != -1) { if (jobCancelled) { throw new Exception("job Cancelled"); } cout.write(buffer, 0, read); read = fin.read(buffer); } } finally { try { fin.close(); } catch (Exception ignore) { } try { cout.close(); } catch (Exception ignore) { } } }
From source file:pro.hirooka.streaming_server_for_multiple_platforms.Encrypter.java
@SuppressWarnings("resource") public void run() { SingletonForSSFMP info = null;/* ww w.j a v a 2s.c om*/ SingletonForSSFMP2 info2 = null; SingletonForSSFMP3 info3 = null; switch (abs) { case 0: info = SingletonForSSFMP.getInstance(); break; case 1: info2 = SingletonForSSFMP2.getInstance(); break; case 2: info3 = SingletonForSSFMP3.getInstance(); break; default: //info = SingletonForMyStreamer.getInstance(); break; } int seqTsEnc = 0; //info.getSeqTsEnc(); if (!modeLive.equals("capturedTimeShifted")) { if ((abs == 0) && (info != null)) { seqTsEnc = info.getSeqTsEnc(); } else if ((abs == 1) && (info2 != null)) { seqTsEnc = info2.getSeqTsEnc(); } else if ((abs == 2) && (info3 != null)) { seqTsEnc = info3.getSeqTsEnc(); } } else if (modeLive.equals("capturedTimeShifted")) { if ((abs == 0) && (info != null)) { seqTsEnc = info.getSeqTsCapturedTimeShifted(); } else if ((abs == 1) && (info2 != null)) { seqTsEnc = info2.getSeqTsCapturedTimeShifted(); } else if ((abs == 2) && (info3 != null)) { seqTsEnc = info3.getSeqTsCapturedTimeShifted(); } } if ((abs == 0) && (info != null) && info.getFlagLastTs()) { seqTsEnc = info.getSeqTsLast(); } else if ((abs == 1) && (info2 != null) && info2.getFlagLastTs()) { seqTsEnc = info2.getSeqTsLast(); } else if ((abs == 2) && (info3 != null) && info3.getFlagLastTs()) { seqTsEnc = info3.getSeqTsLast(); } log.debug(MARKER_Encrypter, "{} Begin : Encryption of seqTsEnc : {}", Thread.currentThread().getStackTrace()[1].getMethodName(), seqTsEnc); Key sKey; Cipher c; FileOutputStream keyOut; FileWriter ivOut; FileInputStream fis; BufferedInputStream bis; FileOutputStream fos; CipherOutputStream cos; try { Security.addProvider(new org.bouncycastle.jce.provider.BouncyCastleProvider()); sKey = makeKey(128); // Key length is 128bit c = Cipher.getInstance("AES/CBC/PKCS7Padding", "BC"); // log.debug(MARKER_Encrypter, "{} [c.getAlgorithm()] {}", Thread.currentThread().getStackTrace()[1].getMethodName(), c.getAlgorithm()); c.init(Cipher.ENCRYPT_MODE, sKey); // Set Key File Name at random String keyPre = RandomStringUtils.randomAlphabetic(10); keyOut = new FileOutputStream(streamPath + FILE_SEPARATOR + keyPre + seqTsEnc + ".key"); if ((abs == 0) && (info != null)) { info.addKeyArrayList(keyPre); } else if ((abs == 1) && (info2 != null)) { info2.addKeyArrayList(keyPre); } else if ((abs == 2) && (info3 != null)) { info3.addKeyArrayList(keyPre); } byte[] keyOutByte = sKey.getEncoded(); keyOut.write(keyOutByte); keyOut.close(); byte[] iv = c.getIV(); // log.debug(MARKER_Encrypter, "{} [iv.length] {} [byte]", Thread.currentThread().getStackTrace()[1].getMethodName(), iv.length); String ivHex = ""; for (int i = 0; i < iv.length; i++) { String ivHexTmp = String.format("%02x", iv[i]).toUpperCase(); ivHex = ivHex + ivHexTmp; } String ivPre = RandomStringUtils.randomAlphabetic(10); ivOut = new FileWriter(streamPath + FILE_SEPARATOR + ivPre + seqTsEnc + ".iv"); ivOut.write(ivHex); ivOut.close(); // log.debug(MARKER_Encrypter, "{} [iv] {}", Thread.currentThread().getStackTrace()[1].getMethodName(), ivHex); if ((abs == 0) && (info != null)) { info.addIvArrayList(ivHex); } else if ((abs == 1) && (info2 != null)) { info2.addIvArrayList(ivHex); } else if ((abs == 2) && (info3 != null)) { info3.addIvArrayList(ivHex); } fis = new FileInputStream(TEMP_PATH_FOR_ENC + FILE_SEPARATOR + "fileSequence" + seqTsEnc + ".ts"); bis = new BufferedInputStream(fis); fos = new FileOutputStream(streamPath + FILE_SEPARATOR + "fileSequenceEnc" + seqTsEnc + ".ts"); cos = new CipherOutputStream(fos, c); if (modeLive.equals("capturedTimeShifted")) { fis = new FileInputStream( TEMP_PATH_FOR_ENC + FILE_SEPARATOR + "fileSequenceEncoded" + seqTsEnc + ".ts"); bis = new BufferedInputStream(fis); fos = new FileOutputStream(streamPath + FILE_SEPARATOR + "fileSequenceEnc" + seqTsEnc + ".ts"); cos = new CipherOutputStream(fos, c); } byte[] buf = new byte[TS_PACKET_LENGTH]; int ch; while ((ch = bis.read(buf)) != -1) { cos.write(buf, 0, ch); } cos.close(); fos.close(); bis.close(); fis.close(); log.debug(MARKER_Encrypter, "{} End : Encryption of seqTsEnc : {}", Thread.currentThread().getStackTrace()[1].getMethodName(), seqTsEnc); if ((abs == 0) && (info != null) && info.getFlagLastTs()) { log.debug(MARKER_Encrypter, "{} ALL ENCRYPTION FINISHED!!! {}", Thread.currentThread().getStackTrace()[1].getMethodName(), abs); } else if ((abs == 1) && (info2 != null) && info2.getFlagLastTs()) { log.debug(MARKER_Encrypter, "{} ALL ENCRYPTION FINISHED!!! {}", Thread.currentThread().getStackTrace()[1].getMethodName(), abs); } else if ((abs == 2) && (info3 != null) && info3.getFlagLastTs()) { log.debug(MARKER_Encrypter, "{} ALL ENCRYPTION FINISHED!!! {}", Thread.currentThread().getStackTrace()[1].getMethodName(), abs); } } catch (NoSuchProviderException e) { e.printStackTrace(); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } catch (NoSuchPaddingException e) { e.printStackTrace(); } catch (InvalidKeyException e) { e.printStackTrace(); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } // try }