List of usage examples for javax.crypto CipherOutputStream CipherOutputStream
public CipherOutputStream(OutputStream os, Cipher c)
From source file:MegaHandler.java
public void download(String url, String path) throws NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException, InvalidAlgorithmParameterException, IOException, IllegalBlockSizeException, BadPaddingException { //TODO DOWNLOAD mismatch? print("Download started"); String[] s = url.split("!"); String file_id = s[1];//from w ww .j a v a 2 s. c om byte[] file_key = MegaCrypt.base64_url_decode_byte(s[2]); int[] intKey = MegaCrypt.aByte_to_aInt(file_key); JSONObject json = new JSONObject(); try { json.put("a", "g"); json.put("g", "1"); json.put("p", file_id); } catch (JSONException e) { e.printStackTrace(); } JSONObject file_data = new JSONObject(api_request(json.toString())); int[] keyNOnce = new int[] { intKey[0] ^ intKey[4], intKey[1] ^ intKey[5], intKey[2] ^ intKey[6], intKey[3] ^ intKey[7], intKey[4], intKey[5] }; byte[] key = MegaCrypt.aInt_to_aByte(keyNOnce[0], keyNOnce[1], keyNOnce[2], keyNOnce[3]); int[] iiv = new int[] { keyNOnce[4], keyNOnce[5], 0, 0 }; byte[] iv = MegaCrypt.aInt_to_aByte(iiv); @SuppressWarnings("unused") int file_size = file_data.getInt("s"); String attribs = (file_data.getString("at")); attribs = new String(MegaCrypt.aes_cbc_decrypt(MegaCrypt.base64_url_decode_byte(attribs), key)); String file_name = attribs.substring(10, attribs.lastIndexOf("\"")); print(file_name); final IvParameterSpec ivSpec = new IvParameterSpec(iv); final SecretKeySpec skeySpec = new SecretKeySpec(key, "AES"); Cipher cipher = Cipher.getInstance("AES/CTR/nopadding"); cipher.init(Cipher.ENCRYPT_MODE, skeySpec, ivSpec); InputStream is = null; String file_url = file_data.getString("g"); FileOutputStream fos = new FileOutputStream(path + File.separator + file_name); final OutputStream cos = new CipherOutputStream(fos, cipher); final Cipher decipher = Cipher.getInstance("AES/CTR/NoPadding"); decipher.init(Cipher.ENCRYPT_MODE, skeySpec, ivSpec); int read = 0; final byte[] buffer = new byte[32767]; try { URLConnection urlConn = new URL(file_url).openConnection(); print(file_url); is = urlConn.getInputStream(); while ((read = is.read(buffer)) > 0) { cos.write(buffer, 0, read); } } finally { try { cos.close(); if (is != null) { is.close(); } } finally { if (fos != null) { fos.close(); } } } print("Download finished"); }
From source file:cd.education.data.collector.android.utilities.EncryptionUtils.java
private static void encryptFile(File file, EncryptedFormInformation formInfo) throws IOException, EncryptionException { File encryptedFile = new File(file.getParentFile(), file.getName() + ".enc"); if (encryptedFile.exists() && !encryptedFile.delete()) { throw new IOException( "Cannot overwrite " + encryptedFile.getAbsolutePath() + ". Perhaps the file is locked?"); }/*from w ww .ja va2s . co m*/ // add elementSignatureSource for this file... formInfo.appendFileSignatureSource(file); RandomAccessFile randomAccessFile = null; CipherOutputStream cipherOutputStream = null; try { Cipher c = formInfo.getCipher(); randomAccessFile = new RandomAccessFile(encryptedFile, "rws"); ByteArrayOutputStream encryptedData = new ByteArrayOutputStream(); cipherOutputStream = new CipherOutputStream(encryptedData, c); InputStream fin = new FileInputStream(file); byte[] buffer = new byte[2048]; int len = fin.read(buffer); while (len != -1) { cipherOutputStream.write(buffer, 0, len); len = fin.read(buffer); } fin.close(); cipherOutputStream.flush(); cipherOutputStream.close(); randomAccessFile.write(encryptedData.toByteArray()); Log.i(t, "Encrpyted:" + file.getName() + " -> " + encryptedFile.getName()); } catch (Exception e) { String msg = "Error encrypting: " + file.getName() + " -> " + encryptedFile.getName(); Log.e(t, msg, e); e.printStackTrace(); throw new EncryptionException(msg, e); } finally { IOUtils.closeQuietly(cipherOutputStream); if (randomAccessFile != null) { randomAccessFile.close(); } } }
From source file:nl.afas.cordova.plugin.secureLocalStorage.SecureLocalStorage.java
private void writeAndEncryptStorage(KeyStore keyStore, HashMap<String, String> hashMap) throws SecureLocalStorageException { try {// w ww . j a v a 2 s . co m ByteArrayOutputStream bos = new ByteArrayOutputStream(); try { ObjectOutputStream oos = new ObjectOutputStream(bos); try { oos.writeObject(hashMap); } finally { oos.close(); } } finally { bos.close(); } SecretKey key = getSecretKey(keyStore); Cipher input = Cipher.getInstance("DES"); input.init(Cipher.ENCRYPT_MODE, key); // encrypt the hashmap FileOutputStream fos = _cordova.getActivity().openFileOutput(SECURELOCALSTORAGEFILE, Context.MODE_PRIVATE); try { CipherOutputStream cipherOutputStream = new CipherOutputStream(fos, input); try { cipherOutputStream.write(bos.toByteArray()); } finally { cipherOutputStream.flush(); cipherOutputStream.close(); } } finally { fos.flush(); fos.close(); } } catch (Exception e) { Log.e("SecureStorage", "Write", e); throw new SecureLocalStorageException("Error encrypting storage", e); } }
From source file:compiler.downloader.MegaHandler.java
private String download(String url, String path, boolean verbose) throws NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException, InvalidAlgorithmParameterException, IOException, IllegalBlockSizeException, BadPaddingException, JSONException { String[] s = url.split("!"); String file_id = s[1];/*from ww w .ja va2 s . c o m*/ byte[] file_key = MegaCrypt.base64_url_decode_byte(s[2]); int[] intKey = MegaCrypt.aByte_to_aInt(file_key); JSONObject json = new JSONObject(); try { json.put("a", "g"); json.put("g", "1"); json.put("p", file_id); } catch (JSONException e) { e.printStackTrace(); } JSONObject file_data = new JSONObject(api_request(json.toString())); int[] keyNOnce = new int[] { intKey[0] ^ intKey[4], intKey[1] ^ intKey[5], intKey[2] ^ intKey[6], intKey[3] ^ intKey[7], intKey[4], intKey[5] }; byte[] key = MegaCrypt.aInt_to_aByte(keyNOnce[0], keyNOnce[1], keyNOnce[2], keyNOnce[3]); int[] iiv = new int[] { keyNOnce[4], keyNOnce[5], 0, 0 }; byte[] iv = MegaCrypt.aInt_to_aByte(iiv); int file_size = file_data.getInt("s"); String attribs = (file_data.getString("at")); attribs = new String(MegaCrypt.aes_cbc_decrypt(MegaCrypt.base64_url_decode_byte(attribs), key)); //print(attribs.substring(4, attribs.length())); String file_name = new JSONObject(attribs.substring(4, attribs.length())).getString("n"); //print("Filename->>" +file_name); final IvParameterSpec ivSpec = new IvParameterSpec(iv); final SecretKeySpec skeySpec = new SecretKeySpec(key, "AES"); Cipher cipher = Cipher.getInstance("AES/CTR/nopadding"); cipher.init(Cipher.ENCRYPT_MODE, skeySpec, ivSpec); InputStream is = null; String file_url = null; try { file_url = file_data.getString("g"); } catch (JSONException e) { e.printStackTrace(); } FileOutputStream fos = new FileOutputStream(path + File.separator + file_name); final OutputStream cos = new CipherOutputStream(fos, cipher); final Cipher decipher = Cipher.getInstance("AES/CTR/NoPadding"); decipher.init(Cipher.ENCRYPT_MODE, skeySpec, ivSpec); int read; final byte[] buffer = new byte[32767]; try { URLConnection urlConn = new URL(file_url).openConnection(); ProgressBar bar = new ProgressBar(); //print(file_url); if (verbose) { bar.update(0, file_size, ""); } //print("FILESIZE:" +file_size); is = urlConn.getInputStream(); long mDownloaded = 0; double current_speed; long startTime = System.nanoTime(); final double NANOS_PER_SECOND = 1000000000.0; final double BYTES_PER_MIB = 1024 * 1024; while ((read = is.read(buffer, 0, 1024)) > 0) { cos.write(buffer, 0, read); mDownloaded += read; //print(mDownloaded); long timeInSecs = (System.nanoTime() - startTime + 1); //print("Debug:" + mDownloaded + "/" + timeInSecs); current_speed = NANOS_PER_SECOND / BYTES_PER_MIB * mDownloaded / (timeInSecs); //print("Speed: "+ (current_speed) + " Mbps"); if (verbose) { bar.update(mDownloaded, file_size, String.format("%.2f", current_speed) + " Mbps"); } } } finally { try { cos.close(); if (is != null) { is.close(); } } finally { if (fos != null) { fos.close(); } } } return file_name; }
From source file:com.zacwolf.commons.crypto._CRYPTOfactory.java
public final void encryptObjToOutputStream(final Serializable obj, final OutputStream outputStream) throws InvalidKeyException, NoSuchAlgorithmException, NoSuchPaddingException, InvalidAlgorithmParameterException, IOException { if (outputStream instanceof ObjectOutputStream) throw new IOException( "encryptObjToOutputStream already wraps the outputStream in an ObjectOutputStream, so only pass-in a non-ObjectOutputStream wrapped stream"); ready();/*from w ww. j a v a 2 s . c om*/ activecrypts++; try { final Cipher ecipher = crypter.getEcipher(); final byte[] salt = ecipher.getIV(); if (salt == null) { outputStream.write(0); } else { outputStream.write(salt.length); for (byte s : salt) outputStream.write(s); } final CipherOutputStream cos = 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(); } } }; final ObjectOutputStream oos = new ObjectOutputStream(cos); oos.writeObject(obj); oos.flush(); oos.close(); } finally { activecrypts--; } }
From source file:com.stimulus.archiva.store.MessageStore.java
/** * Get a raw output stream for a message * @param messageFileName The file name of the message * @param compress Should compress message * @param encrypt Should encrypt message * @return An outputstream directed to the message *//*from w w w. j a va 2s.c o m*/ public OutputStream getRawMessageOutputStream(File messageFile, boolean compress, boolean encrypt) throws IOException, MessageStoreException { if (messageFile == null) throw new MessageStoreException("assertion failure: null messageFileName", logger); OutputStream os = new BufferedOutputStream(new FileOutputStream(messageFile)); Cipher ecipher = null; if (encrypt) { try { ecipher = Cipher.getInstance(key.getAlgorithm()); ecipher.init(Cipher.ENCRYPT_MODE, key, paramSpec); } catch (Exception e) { logger.fatal( "Please ensure you have the Java Cryptography Extension (JCE) Unlimited Strength Jurisdiction Policy Files installed."); logger.fatal("Visit http://java.sun.com2/javase/downloads/index.jsp to download them."); throw new MessageStoreException("failed to initalize cipher. Cause:", e, logger); } os = new CipherOutputStream(os, ecipher); } if (compress) os = new GZIPOutputStream(os); return os; }
From source file:org.cryptomator.crypto.aes256.Aes256Cryptor.java
@Override public Long encryptFile(InputStream plaintextFile, SeekableByteChannel encryptedFile) throws IOException { // truncate file encryptedFile.truncate(0);// w ww . ja v a 2 s . c o m // use an IV, whose last 8 bytes store a long used in counter mode and write initial value to file. final ByteBuffer countingIv = ByteBuffer.wrap(randomData(AES_BLOCK_LENGTH)); countingIv.putLong(AES_BLOCK_LENGTH - Long.BYTES, 0l); countingIv.position(0); encryptedFile.write(countingIv); // init crypto stuff: final Mac mac = this.hmacSha256(hMacMasterKey); final Cipher cipher = this.aesCtrCipher(primaryMasterKey, countingIv.array(), Cipher.ENCRYPT_MODE); // init mac buffer and skip 32 bytes final ByteBuffer macBuffer = ByteBuffer.allocate(mac.getMacLength()); encryptedFile.write(macBuffer); // init filesize buffer and skip 16 bytes final ByteBuffer encryptedFileSizeBuffer = ByteBuffer.allocate(AES_BLOCK_LENGTH); encryptedFile.write(encryptedFileSizeBuffer); // write content: final OutputStream out = new SeekableByteChannelOutputStream(encryptedFile); final OutputStream macOut = new MacOutputStream(out, mac); final OutputStream cipheredOut = new CipherOutputStream(macOut, cipher); final OutputStream blockSizeBufferedOut = new BufferedOutputStream(cipheredOut, AES_BLOCK_LENGTH); final Long plaintextSize = IOUtils.copyLarge(plaintextFile, blockSizeBufferedOut); // ensure total byte count is a multiple of the block size, in CTR mode: final int remainderToFillLastBlock = AES_BLOCK_LENGTH - (int) (plaintextSize % AES_BLOCK_LENGTH); blockSizeBufferedOut.write(new byte[remainderToFillLastBlock]); // append a few blocks of fake data: final int numberOfPlaintextBlocks = (int) Math.ceil(plaintextSize / AES_BLOCK_LENGTH); final int upToTenPercentFakeBlocks = (int) Math.ceil(Math.random() * 0.1 * numberOfPlaintextBlocks); final byte[] emptyBytes = new byte[AES_BLOCK_LENGTH]; for (int i = 0; i < upToTenPercentFakeBlocks; i += AES_BLOCK_LENGTH) { blockSizeBufferedOut.write(emptyBytes); } blockSizeBufferedOut.flush(); // write MAC of total ciphertext: macBuffer.position(0); macBuffer.put(mac.doFinal()); macBuffer.position(0); encryptedFile.position(16); // right behind the IV encryptedFile.write(macBuffer); // 256 bit MAC // encrypt and write plaintextSize try { final ByteBuffer fileSizeBuffer = ByteBuffer.allocate(Long.BYTES); fileSizeBuffer.putLong(plaintextSize); final Cipher sizeCipher = aesEcbCipher(primaryMasterKey, Cipher.ENCRYPT_MODE); final byte[] encryptedFileSize = sizeCipher.doFinal(fileSizeBuffer.array()); encryptedFileSizeBuffer.position(0); encryptedFileSizeBuffer.put(encryptedFileSize); encryptedFileSizeBuffer.position(0); encryptedFile.position(48); // right behind the IV and MAC encryptedFile.write(encryptedFileSizeBuffer); } catch (IllegalBlockSizeException | BadPaddingException e) { throw new IllegalStateException( "Block size must be valid, as padding is requested. BadPaddingException not possible in encrypt mode.", e); } return plaintextSize; }
From source file:net.tawacentral.roger.secrets.FileUtils.java
/** * Returns an encrypted json stream representing the user's secrets. * * @param cipher// ww w.j ava 2s . c o m * The encryption cipher to use with the file. * @param secrets * The list of secrets. * @return byte array of secrets * @throws IOException * if any error occurs */ public static byte[] toEncryptedJSONSecretsStream(Cipher cipher, ArrayList<Secret> secrets) throws IOException { CipherOutputStream output = null; ByteArrayOutputStream baos = new ByteArrayOutputStream(); try { output = new CipherOutputStream(baos, cipher); output.write(FileUtils.toJSONSecrets(secrets).toString().getBytes("UTF-8")); } catch (Exception e) { Log.e(LOG_TAG, "toEncryptedJSONSecretsStream", e); throw new IOException("toEncryptedJSONSecretsStream failed: " + e.getMessage()); } finally { try { if (null != output) output.close(); } catch (IOException ex) { } } return baos.toByteArray(); }
From source file:com.pari.nm.utils.backup.BackupRestore.java
private void encrypt(File backupZipFile, File encrBackupZipFile) throws Exception { try {// w w w .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) { } } }