List of usage examples for javax.crypto CipherOutputStream close
public void close() throws IOException
From source file:org.yes.cart.web.support.util.cookie.impl.CookieTuplizerImpl.java
/** * {@inheritDoc}/* w ww. ja v a2 s . c om*/ */ public Cookie[] toCookies(final Cookie[] oldCookies, final Serializable serializable) throws UnableToCookielizeObjectException { ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(); synchronized (desCipher) { BASE64EncoderStream base64EncoderStream = new BASE64EncoderStream(byteArrayOutputStream, Integer.MAX_VALUE); //will be splited manually CipherOutputStream cipherOutputStream = new CipherOutputStream(base64EncoderStream, desCipher); ObjectOutputStream objectOutputStream = null; try { objectOutputStream = new ObjectOutputStream(cipherOutputStream); objectOutputStream.writeObject(serializable); objectOutputStream.flush(); objectOutputStream.close(); } catch (Throwable ioe) { ShopCodeContext.getLog(this) .error(MessageFormat.format("Unable to serialize object {0}", serializable), ioe); throw new UnableToCookielizeObjectException(ioe); } finally { try { if (objectOutputStream != null) { objectOutputStream.close(); } cipherOutputStream.close(); base64EncoderStream.close(); byteArrayOutputStream.close(); } catch (IOException e) { ShopCodeContext.getLog(this).error("Can not close stream", e); } } } return assembleCookiesForObject(oldCookies, split(byteArrayOutputStream.toString()), serializable); }
From source file:org.openchaos.android.fooping.service.PingService.java
private void sendMessage(final JSONObject json) { boolean encrypt = prefs.getBoolean("SendAES", false); boolean compress = prefs.getBoolean("SendGZIP", false); String exchangeHost = prefs.getString("ExchangeHost", null); int exchangePort = Integer.valueOf(prefs.getString("ExchangePort", "-1")); if (encrypt) { if (skeySpec == null) { try { skeySpec = new SecretKeySpec(MessageDigest.getInstance("SHA-256") .digest(prefs.getString("ExchangeKey", null).getBytes("US-ASCII")), "AES"); } catch (Exception e) { Log.e(tag, e.toString()); e.printStackTrace();/*from w ww .j a v a 2 s. c o m*/ } } if (cipher == null) { try { cipher = Cipher.getInstance("AES/CFB8/NoPadding"); } catch (Exception e) { Log.e(tag, e.toString()); e.printStackTrace(); } } if (skeySpec == null || cipher == null) { Log.e(tag, "Encryption requested but not available"); throw new AssertionError(); } } if (exchangeHost == null || exchangePort <= 0 || exchangePort >= 65536) { Log.e(tag, "Invalid server name or port"); throw new AssertionError(); } try { ByteArrayOutputStream baos = new ByteArrayOutputStream(); CipherOutputStream cos = null; GZIPOutputStream zos = null; // TODO: send protocol header to signal compression & encryption if (encrypt) { cipher.init(Cipher.ENCRYPT_MODE, skeySpec); cos = new CipherOutputStream(baos, cipher); // write iv block baos.write(cipher.getIV()); } final byte[] message = new JSONArray().put(json).toString().getBytes(); if (compress) { zos = new GZIPOutputStream((encrypt) ? (cos) : (baos)); zos.write(message); zos.finish(); zos.close(); if (encrypt) { cos.close(); } } else if (encrypt) { cos.write(message); cos.close(); } else { baos.write(message); } baos.flush(); final byte[] output = baos.toByteArray(); baos.close(); // path MTU is the actual limit here, not only local MTU // TODO: make packet fragmentable (clear DF flag) if (output.length > 1500) { Log.w(tag, "Message probably too long: " + output.length + " bytes"); } DatagramSocket socket = new DatagramSocket(); // socket.setTrafficClass(0x04 | 0x02); // IPTOS_RELIABILITY | IPTOS_LOWCOST socket.send( new DatagramPacket(output, output.length, InetAddress.getByName(exchangeHost), exchangePort)); socket.close(); Log.d(tag, "message sent: " + output.length + " bytes (raw: " + message.length + " bytes)"); } catch (Exception e) { Log.e(tag, e.toString()); e.printStackTrace(); } }
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. * // w ww . ja v a 2 s .c o m * @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 {/*from www .j a v a2 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:uk.ac.ox.webauth.Token.java
/** * Encode the token and return it./*w w w . j a v a 2 s.co m*/ * @param sessionKey The session key to use to AES encrypt and feed the HMAC. * @return The escaped, encrypted and base64 encoded token. * @throws GeneralSecurityException if there was a problem with the security code used. */ public String encrypt(Key sessionKey) throws GeneralSecurityException { // a token is: // {key-hint}{nonce }{hmac }{token-attributes }{padding } // {4 bytes }{16 bytes}{20 bytes}{make the data into multiple of 16 bytes} // everything after the key hint is aes encrypted // this is where we want to final data packet to end up ByteArrayOutputStream data = new ByteArrayOutputStream(); try { data.write(unixTimestampBytes(System.currentTimeMillis())); // set up the AES encryption Cipher cipher = Cipher.getInstance("AES/CBC/NoPadding"); cipher.init(ENCRYPT_MODE, sessionKey, IV); CipherOutputStream encrypt = new CipherOutputStream(data, cipher); // write the nonce byte[] nonce = new byte[16]; RAND.nextBytes(nonce); encrypt.write(nonce); // put together the actual key-value pair data to send ByteArrayOutputStream paddedKeyValueData = new ByteArrayOutputStream(); for (KeyValuePair kvp : kv.values()) { paddedKeyValueData.write(kvp.bytes()); } // and pad it (including the size of the hmac to be added later) int padding = 16 - ((20 + paddedKeyValueData.size()) % 16); for (int i = 0; i < padding; i++) { paddedKeyValueData.write(padding); } byte[] paddedKeyValueDataArray = paddedKeyValueData.toByteArray(); // then work out and write the SHA1 HMAC Mac hmacSHA1 = Mac.getInstance("HmacSHA1"); hmacSHA1.init(sessionKey); encrypt.write(hmacSHA1.doFinal(paddedKeyValueDataArray)); // then write the actual key-value pair data and padding and close it encrypt.write(paddedKeyValueDataArray); encrypt.close(); } catch (IOException ioe) { /* should never happen as it's a ByteArrayOutputStream */ ioe.printStackTrace(); } // return the token after base64 encoding it return new String(Base64.encodeBase64(data.toByteArray())); }
From source file:com.zacwolf.commons.crypto._CRYPTOfactory.java
public final void encryptToOutputStream(final byte[] bytes, final OutputStream outputStream) throws InvalidKeyException, NoSuchAlgorithmException, NoSuchPaddingException, InvalidAlgorithmParameterException, IOException { ready();/*from w ww. j av a2s . c o m*/ activecrypts++; try { final Cipher ecipher = crypter.getEcipher(); final byte[] salt = ecipher.getIV(); if (salt == null) { outputStream.write(0); } else { outputStream.write(salt.length); outputStream.write(salt); } outputStream.flush(); CipherOutputStream cop = null; try { cop = new CipherOutputStream(outputStream, ecipher) { /* * WebSphere 7 has a known bug with it's implementation of ibmjceprovider.jar * concerning writing byte-arrays in a serialized object when the byte-array length * is zero. * see: http://www.ibm.com/developerworks/forums/thread.jspa?messageID=14597510 * * Added an override of the CipherOutputStream write method so that it is only called when * the byte array has length > 0 */ @Override public void write(final byte[] b, final int off, final int len) throws IOException { if (len > 0) { super.write(b, off, len); //super.flush(); Do NOT flush here, as it slows the process down exponentially } } }; cop.write(bytes); cop.flush(); } finally { if (cop != null) { cop.flush(); cop.close(); } outputStream.flush(); outputStream.close(); } } finally { activecrypts--; } }
From source file:edu.ncsu.asbransc.mouflon.recorder.UploadFile.java
protected void doUpload() { DbAdapter dba = new DbAdapter(this); dba.open();//from w ww .j a va 2 s . c o m Cursor allLogs = dba.fetchAll(); StringBuilder sb = new StringBuilder(); allLogs.moveToFirst(); sb.append("DateTime"); sb.append(","); sb.append("Process"); sb.append(","); sb.append("Type"); sb.append(","); sb.append("Component"); sb.append(","); sb.append("ActionString"); sb.append(","); sb.append("Category"); sb.append("\n"); while (!allLogs.isAfterLast()) { sb.append(allLogs.getString(allLogs.getColumnIndex(DbAdapter.KEY_TIME))); sb.append(","); sb.append(allLogs.getString(allLogs.getColumnIndex(DbAdapter.KEY_PROCESSTAG))); sb.append(","); sb.append(allLogs.getString(allLogs.getColumnIndex(DbAdapter.KEY_EXTRA_1))); sb.append(","); sb.append(allLogs.getString(allLogs.getColumnIndex(DbAdapter.KEY_EXTRA_2))); sb.append(","); sb.append(allLogs.getString(allLogs.getColumnIndex(DbAdapter.KEY_EXTRA_3))); sb.append(","); sb.append(allLogs.getString(allLogs.getColumnIndex(DbAdapter.KEY_EXTRA_4))); sb.append("\n"); allLogs.moveToNext(); } dba.close(); File appDir = getDir("toUpload", MODE_PRIVATE); UUID uuid; uuid = MainScreen.getOrCreateUUID(this); long time = System.currentTimeMillis(); String basename = uuid.toString() + "_AT_" + time; String filename = basename + ".zip.enc"; File file = new File(appDir, filename); FileOutputStream out = null; ZipOutputStream outzip = null; CipherOutputStream outcipher = null; Cipher datac = null; File keyfile = new File(appDir, basename + ".key.enc"); //Log.i("sb length", Integer.toString(sb.length())); SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this); String email = prefs.getString(MainScreen.EMAIL_KEY, ""); String emailFilename = "email.txt"; String csvFilename = "mouflon_log_" + time + ".csv"; try { SecretKey aeskey = generateAESKey(); //Log.i("secret key", bytearrToString(aeskey.getEncoded())); encryptAndWriteAESKey(aeskey, keyfile); datac = Cipher.getInstance("AES/CBC/PKCS5Padding", "BC"); byte[] ivbytes = genIV(); IvParameterSpec iv = new IvParameterSpec(ivbytes); datac.init(Cipher.ENCRYPT_MODE, aeskey, iv); out = new FileOutputStream(file); out.write(ivbytes); //Log.i("iv bytes", bytearrToString(ivbytes)); outcipher = new CipherOutputStream(out, datac); outzip = new ZipOutputStream(outcipher); outzip.setMethod(ZipOutputStream.DEFLATED); //write the first file (e-mail address) String androidVersion = android.os.Build.VERSION.RELEASE; String deviceName = android.os.Build.MODEL; ZipEntry infoEntry = new ZipEntry("info.txt"); outzip.putNextEntry(infoEntry); outzip.write((androidVersion + "\n" + deviceName).getBytes()); outzip.closeEntry(); ZipEntry emailEntry = new ZipEntry(emailFilename); outzip.putNextEntry(emailEntry); outzip.write(email.getBytes()); outzip.closeEntry(); ZipEntry csvEntry = new ZipEntry(csvFilename); outzip.putNextEntry(csvEntry); outzip.write(sb.toString().getBytes()); outzip.closeEntry(); } catch (Exception e) { e.printStackTrace(); } finally { try { outzip.close(); outcipher.close(); out.close(); } catch (IOException e) { //ignore } catch (NullPointerException ne) { //ignore } } //here we actually upload the files String containerFilename = basename + "_container.zip"; File containerFile = new File(appDir, containerFilename); zipUp(containerFile, new File[] { file, keyfile }); boolean success = uploadFile(containerFile); containerFile.delete(); file.delete(); keyfile.delete(); if (success && prefs.getBoolean(MainScreen.DELETE_KEY, true)) { DbAdapter dba2 = new DbAdapter(this); dba2.open(); dba2.clearDB(); dba2.close(); } if (!success && prefs.getBoolean(MainScreen.UPLOAD_KEY, false)) { Editor e = prefs.edit(); e.putInt(MainScreen.DAY_KEY, 6); //reset it to run tomorrow if it fails e.commit(); } String s = success ? "Upload complete. Thanks!" : "Upload Failed"; NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(UploadFile.this) .setSmallIcon(R.drawable.ic_launcher_bw).setContentTitle("Mouflon Recorder").setContentText(s) .setAutoCancel(true).setOngoing(false); if (mManual) { //only show a notification if we manually upload the file. Intent toLaunch = new Intent(UploadFile.this, MainScreen.class); //The notification has to go somewhere. PendingIntent pi = PendingIntent.getActivity(UploadFile.this, 0, toLaunch, PendingIntent.FLAG_UPDATE_CURRENT); mBuilder.setContentIntent(pi); NotificationManager manager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE); manager.notify(1, mBuilder.build()); } stopSelf(); }
From source file:pro.hirooka.streaming_server_for_multiple_platforms.Encrypter.java
@SuppressWarnings("resource") public void run() { SingletonForSSFMP info = null;//from w w w . jav a 2 s . c o m 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 }