List of usage examples for org.bouncycastle.crypto.modes CBCBlockCipher CBCBlockCipher
public CBCBlockCipher(BlockCipher cipher)
From source file:freemail.RTSFetcher.java
License:Open Source License
private byte[] decrypt_rts(File rtsmessage) throws IOException, InvalidCipherTextException { // initialise our ciphers RSAKeyParameters ourprivkey = AccountManager.getPrivateKey(account.getProps()); AsymmetricBlockCipher deccipher = new RSAEngine(); deccipher.init(false, ourprivkey);// w ww. j ava 2 s . co m PaddedBufferedBlockCipher aescipher = new PaddedBufferedBlockCipher(new CBCBlockCipher(new AESEngine()), new PKCS7Padding()); // first n bytes will be an encrypted RSA block containting the // AES IV and Key. Read that. byte[] encrypted_params = new byte[deccipher.getInputBlockSize()]; FileInputStream fis = new FileInputStream(rtsmessage); int read = 0; while (read < encrypted_params.length) { read += fis.read(encrypted_params, read, encrypted_params.length - read); if (read < 0) break; } if (read < 0) { throw new InvalidCipherTextException("RTS Message too short"); } byte[] aes_iv_and_key = deccipher.processBlock(encrypted_params, 0, encrypted_params.length); KeyParameter kp = new KeyParameter(aes_iv_and_key, aescipher.getBlockSize(), aes_iv_and_key.length - aescipher.getBlockSize()); ParametersWithIV kpiv = new ParametersWithIV(kp, aes_iv_and_key, 0, aescipher.getBlockSize()); try { aescipher.init(false, kpiv); } catch (IllegalArgumentException iae) { throw new InvalidCipherTextException(iae.getMessage()); } byte[] plaintext = new byte[aescipher.getOutputSize((int) rtsmessage.length() - read)]; int ptbytes = 0; while (read < rtsmessage.length()) { byte[] buf = new byte[(int) rtsmessage.length() - read]; int thisread = fis.read(buf, 0, (int) rtsmessage.length() - read); ptbytes += aescipher.processBytes(buf, 0, thisread, plaintext, ptbytes); read += thisread; } fis.close(); try { aescipher.doFinal(plaintext, ptbytes); } catch (DataLengthException dle) { throw new InvalidCipherTextException(dle.getMessage()); } return plaintext; }
From source file:heat.crypto.Crypto.java
License:Open Source License
public static byte[] aesEncrypt(byte[] plaintext, byte[] myPrivateKey, byte[] theirPublicKey, byte[] nonce) { try {// w w w. j a va2 s.c om byte[] dhSharedSecret = new byte[32]; Curve25519.curve(dhSharedSecret, myPrivateKey, theirPublicKey); for (int i = 0; i < 32; i++) { dhSharedSecret[i] ^= nonce[i]; } byte[] key = sha256().digest(dhSharedSecret); byte[] iv = new byte[16]; secureRandom.get().nextBytes(iv); PaddedBufferedBlockCipher aes = new PaddedBufferedBlockCipher(new CBCBlockCipher(new AESEngine())); CipherParameters ivAndKey = new ParametersWithIV(new KeyParameter(key), iv); aes.init(true, ivAndKey); byte[] output = new byte[aes.getOutputSize(plaintext.length)]; int ciphertextLength = aes.processBytes(plaintext, 0, plaintext.length, output, 0); ciphertextLength += aes.doFinal(output, ciphertextLength); byte[] result = new byte[iv.length + ciphertextLength]; System.arraycopy(iv, 0, result, 0, iv.length); System.arraycopy(output, 0, result, iv.length, ciphertextLength); return result; } catch (InvalidCipherTextException e) { throw new RuntimeException(e.getMessage(), e); } }
From source file:heat.crypto.Crypto.java
License:Open Source License
public static byte[] aesDecrypt(byte[] ivCiphertext, byte[] myPrivateKey, byte[] theirPublicKey, byte[] nonce) { try {//w ww.j a va2s . c om if (ivCiphertext.length < 16 || ivCiphertext.length % 16 != 0) { throw new InvalidCipherTextException("invalid ciphertext"); } byte[] iv = Arrays.copyOfRange(ivCiphertext, 0, 16); byte[] ciphertext = Arrays.copyOfRange(ivCiphertext, 16, ivCiphertext.length); byte[] dhSharedSecret = new byte[32]; Curve25519.curve(dhSharedSecret, myPrivateKey, theirPublicKey); for (int i = 0; i < 32; i++) { dhSharedSecret[i] ^= nonce[i]; } byte[] key = sha256().digest(dhSharedSecret); PaddedBufferedBlockCipher aes = new PaddedBufferedBlockCipher(new CBCBlockCipher(new AESEngine())); CipherParameters ivAndKey = new ParametersWithIV(new KeyParameter(key), iv); aes.init(false, ivAndKey); byte[] output = new byte[aes.getOutputSize(ciphertext.length)]; int plaintextLength = aes.processBytes(ciphertext, 0, ciphertext.length, output, 0); plaintextLength += aes.doFinal(output, plaintextLength); byte[] result = new byte[plaintextLength]; System.arraycopy(output, 0, result, 0, result.length); return result; } catch (InvalidCipherTextException e) { throw new RuntimeException(e.getMessage(), e); } }
From source file:jd.plugins.hoster.CrunchyRollCom.java
License:Open Source License
/** * Decrypt and convert the downloaded file from CrunchyRoll's own encrypted xml format into its .ass equivalent. * * @param downloadLink/*from w w w. j a va 2 s . c om*/ * The DownloadLink to convert to .ass */ private void convertSubs(final DownloadLink downloadLink) throws PluginException { downloadLink.getLinkStatus().setStatusText("Decrypting subtitles..."); try { final File source = new File(downloadLink.getFileOutput()); final StringBuilder xmltext = new StringBuilder(); final String lineseparator = System.getProperty("line.separator"); Scanner in = null; try { in = new Scanner(new FileReader(source)); while (in.hasNext()) { xmltext.append(in.nextLine() + lineseparator); } } catch (Exception e) { } finally { in.close(); } if (xmltext.toString().contains("<error>No Permission</error>")) { throw new PluginException(LinkStatus.ERROR_FILE_NOT_FOUND); } // Create the XML Parser final DocumentBuilderFactory xmlDocBuilderFactory = DocumentBuilderFactory.newInstance(); final DocumentBuilder xmlDocBuilder = xmlDocBuilderFactory.newDocumentBuilder(); final Document xml = xmlDocBuilder.parse(new File(downloadLink.getFileOutput())); xml.getDocumentElement().normalize(); // Get the subtitle information final Element xmlSub = (Element) xml.getElementsByTagName("subtitle").item(0); final Node error = xmlSub.getAttributeNode("error"); final Node xmlId = xmlSub.getAttributeNode("id"); final Node xmlIv = xmlSub.getElementsByTagName("iv").item(0); final Node xmlData = xmlSub.getElementsByTagName("data").item(0); final int subId = Integer.parseInt(xmlId.getNodeValue()); final String subIv = xmlIv.getTextContent(); final String subData = xmlData.getTextContent(); // Generate the AES parameters final byte[] key = this.subsGenerateKey(subId, 32); final byte[] ivData = DatatypeConverter.parseBase64Binary(subIv); final byte[] encData = DatatypeConverter.parseBase64Binary(subData); byte[] decrypted = null; try { final KeyParameter keyParam = new KeyParameter(key); final CipherParameters cipherParams = new ParametersWithIV(keyParam, ivData); // Prepare the cipher (AES, CBC, no padding) final BufferedBlockCipher cipher = new BufferedBlockCipher(new CBCBlockCipher(new AESEngine())); cipher.reset(); cipher.init(false, cipherParams); // Decrypt the subtitles decrypted = new byte[cipher.getOutputSize(encData.length)]; final int decLength = cipher.processBytes(encData, 0, encData.length, decrypted, 0); cipher.doFinal(decrypted, decLength); } catch (final Throwable e) { logger.severe(e.getMessage()); throw new PluginException(LinkStatus.ERROR_PLUGIN_DEFECT, "Error decrypting subtitles!"); } // Create the XML Parser (and zlib decompress using InflaterInputStream) final DocumentBuilderFactory subsDocBuilderFactory = DocumentBuilderFactory.newInstance(); final DocumentBuilder subsDocBuilder = subsDocBuilderFactory.newDocumentBuilder(); final Document subs = subsDocBuilder .parse(new InflaterInputStream(new ByteArrayInputStream(decrypted))); subs.getDocumentElement().normalize(); // Get the header final Element subHeaderElem = (Element) subs.getElementsByTagName("subtitle_script").item(0); final String subHeaderTitle = subHeaderElem.getAttributeNode("title").getNodeValue(); final String subHeaderWrap = subHeaderElem.getAttributeNode("wrap_style").getNodeValue(); final String subHeaderResX = subHeaderElem.getAttributeNode("play_res_x").getNodeValue(); final String subHeaderResY = subHeaderElem.getAttributeNode("play_res_y").getNodeValue(); final String subHeader = "[Script Info]\nTitle: " + subHeaderTitle + "\nScriptType: v4.00+\nWrapStyle: " + subHeaderWrap + "\nPlayResX: " + subHeaderResX + "\nPlayResY: " + subHeaderResY + "\n"; // Get the styles String subStyles = "[V4 Styles]\nFormat: Name, Fontname, Fontsize, PrimaryColour, SecondaryColour, OutlineColour, BackColour, Bold, Italic, Underline, StrikeOut, ScaleX, ScaleY, Spacing, Angle, BorderStyle, Outline, Shadow, Alignment, MarginL, MarginR, MarginV, Encoding\n"; final NodeList subStylesNodes = subs.getElementsByTagName("style"); for (int i = 0; i < subStylesNodes.getLength(); i++) { final Element subStylesElem = (Element) subStylesNodes.item(i); final String subStylesName = subStylesElem.getAttributeNode("name").getNodeValue(); final String subStylesFontName = subStylesElem.getAttributeNode("font_name").getNodeValue(); final String subStylesFontSize = subStylesElem.getAttributeNode("font_size").getNodeValue(); final String subStylesPriColor = subStylesElem.getAttributeNode("primary_colour").getNodeValue(); final String subStylesSecColor = subStylesElem.getAttributeNode("secondary_colour").getNodeValue(); final String subStylesOutColor = subStylesElem.getAttributeNode("outline_colour").getNodeValue(); final String subStylesBacColor = subStylesElem.getAttributeNode("back_colour").getNodeValue(); final String subStylesUnderline = subStylesElem.getAttributeNode("underline").getNodeValue(); final String subStylesStrikeout = subStylesElem.getAttributeNode("strikeout").getNodeValue(); final String subStylesAlignment = subStylesElem.getAttributeNode("alignment").getNodeValue(); final String subStylesSpacing = subStylesElem.getAttributeNode("spacing").getNodeValue(); final String subStylesItalic = subStylesElem.getAttributeNode("italic").getNodeValue(); String subStylesScaleX = subStylesElem.getAttributeNode("scale_x").getNodeValue(); String subStylesScaleY = subStylesElem.getAttributeNode("scale_y").getNodeValue(); final String subStylesBorder = subStylesElem.getAttributeNode("border_style").getNodeValue(); final String subStylesShadow = subStylesElem.getAttributeNode("shadow").getNodeValue(); final String subStylesBold = subStylesElem.getAttributeNode("bold").getNodeValue(); final String subStylesAngle = subStylesElem.getAttributeNode("angle").getNodeValue(); final String subStylesOutline = subStylesElem.getAttributeNode("outline").getNodeValue(); final String subStylesMarginL = subStylesElem.getAttributeNode("margin_l").getNodeValue(); final String subStylesMarginR = subStylesElem.getAttributeNode("margin_r").getNodeValue(); final String subStylesMarginV = subStylesElem.getAttributeNode("margin_v").getNodeValue(); final String subStylesEncoding = subStylesElem.getAttributeNode("encoding").getNodeValue(); // Fix the odd case where the subtitles are scaled to nothing if (subStylesScaleX.equals("0")) { subStylesScaleX = "100"; } if (subStylesScaleY.equals("0")) { subStylesScaleY = "100"; } subStyles += "Style: " + subStylesName + ", " + subStylesFontName + ", " + subStylesFontSize + ", " + subStylesPriColor + ", " + subStylesSecColor + ", " + subStylesOutColor + ", " + subStylesBacColor + ", " + subStylesBold + ", " + subStylesItalic + ", " + subStylesUnderline + ", " + subStylesStrikeout + ", " + subStylesScaleX + ", " + subStylesScaleY + ", " + subStylesSpacing + ", " + subStylesAngle + ", " + subStylesBorder + ", " + subStylesOutline + ", " + subStylesShadow + ", " + subStylesAlignment + ", " + subStylesMarginL + ", " + subStylesMarginR + ", " + subStylesMarginV + ", " + subStylesEncoding + "\n"; } // Get the elements String subEvents = "[Events]\nFormat: Layer, Start, End, Style, Name, MarginL, MarginR, MarginV, Effect, Text\n"; final NodeList subEventsNodes = subs.getElementsByTagName("event"); for (int i = 0; i < subEventsNodes.getLength(); i++) { final Element subEventsElem = (Element) subEventsNodes.item(i); final String subEventsStart = subEventsElem.getAttributeNode("start").getNodeValue(); final String subEventsEnd = subEventsElem.getAttributeNode("end").getNodeValue(); final String subEventsStyle = subEventsElem.getAttributeNode("style").getNodeValue(); final String subEventsName = subEventsElem.getAttributeNode("name").getNodeValue(); final String subEventsMarginL = subEventsElem.getAttributeNode("margin_l").getNodeValue(); final String subEventsMarginR = subEventsElem.getAttributeNode("margin_r").getNodeValue(); final String subEventsMarginV = subEventsElem.getAttributeNode("margin_v").getNodeValue(); final String subEventsEffect = subEventsElem.getAttributeNode("effect").getNodeValue(); final String subEventsText = subEventsElem.getAttributeNode("text").getNodeValue(); subEvents += "Dialogue: 0," + subEventsStart + "," + subEventsEnd + "," + subEventsStyle + "," + subEventsName + "," + subEventsMarginL + "," + subEventsMarginR + "," + subEventsMarginV + "," + subEventsEffect + "," + subEventsText + "\n"; } // Output to the original file final FileWriter subOutFile = new FileWriter(downloadLink.getFileOutput()); final BufferedWriter subOut = new BufferedWriter(subOutFile); try { subOut.write(subHeader + "\n"); subOut.write(subStyles + "\n"); subOut.write(subEvents); } catch (final Throwable e) { subOut.close(); subOutFile.close(); throw new PluginException(LinkStatus.ERROR_DOWNLOAD_FAILED, "Error writing decrypted subtitles!"); } subOut.close(); subOutFile.close(); downloadLink.getLinkStatus().setStatusText( JDL.L("plugins.hoster.crunchyrollcom.decryptedsubtitles", "Subtitles decrypted")); } catch (final SAXException e) { throw new PluginException(LinkStatus.ERROR_PLUGIN_DEFECT, "Error decrypting subtitles: Invalid XML file!"); } catch (final DOMException e) { throw new PluginException(LinkStatus.ERROR_PLUGIN_DEFECT, "Error decrypting subtitles: XML file changed!"); } catch (final PluginException e) { throw e; } catch (final Throwable e) { e.printStackTrace(); throw new PluginException(LinkStatus.ERROR_PLUGIN_DEFECT, "Error decrypting subtitles!"); } }
From source file:labr_client.Public.encryption.java
License:Open Source License
public static String encode(String dec) throws GeneralSecurityException { // Generate 128 bits of random data for use as the IV. It is important to use a different IV for // each encrypted block of text, to ensure that the same string encrypted by two different people // does not give the same encrypted text string - that leads to obvious attack possibilities. Note // however that the IV does not need to be kept secret; it is a little bit like a 'salt' for a // password, which improves security even when the salt is stored in plaintext in a database or // prefixed to the encrypted file. byte[] ivData = new byte[AES_NIVBITS / 8]; //Hoe groot is deze array -> 128/8 = 16 Random r = new Random(); // Note: no seed here, ie these values are truly random r.nextBytes(ivData);//from ww w. ja v a2 s. c o m //// try { //// System.out.println(new String(ivData, "UTF-8")); // for UTF-8 encoding //// } catch (UnsupportedEncodingException ex) { //// Logger.getLogger(encryption.class.getName()).log(Level.SEVERE, null, ex); //// } // ivData[0] = Byte.valueOf("100"); // ivData[1] = Byte.valueOf("1"); // ivData[2] = Byte.valueOf("15"); // ivData[3] = Byte.valueOf("50"); // ivData[4] = Byte.valueOf("70"); // ivData[5] = Byte.valueOf("80"); // ivData[6] = Byte.valueOf("5"); // ivData[7] = Byte.valueOf("45"); // ivData[8] = Byte.valueOf("100"); // ivData[9] = Byte.valueOf("1"); // ivData[10] = Byte.valueOf("15"); // ivData[11] = Byte.valueOf("50"); // ivData[12] = Byte.valueOf("70"); // ivData[13] = Byte.valueOf("80"); // ivData[14] = Byte.valueOf("5"); // ivData[15] = Byte.valueOf("45"); // Select encryption algorithm and padding : AES with CBC and PCKS#7 //byte[] ivData = new sun.misc.BASE64Decoder().decodeBuffer(salt); BlockCipherPadding padding = new PKCS7Padding(); BufferedBlockCipher cipher = new PaddedBufferedBlockCipher(new CBCBlockCipher(new AESEngine()), padding); // Encrypt the input string using key + iv KeyParameter keyParam = getAesKey(); CipherParameters params = new ParametersWithIV(keyParam, ivData); cipher.reset(); cipher.init(true, params); // first param = encode/decode byte[] bytesDec = dec.getBytes(UTF8); // data to decode byte[] bytesEnc; try { int buflen = cipher.getOutputSize(bytesDec.length); bytesEnc = new byte[buflen]; int nBytesEnc = cipher.processBytes(bytesDec, 0, bytesDec.length, bytesEnc, 0); nBytesEnc += cipher.doFinal(bytesEnc, nBytesEnc); if (nBytesEnc != bytesEnc.length) { throw new IllegalStateException("Unexpected behaviour : getOutputSize value incorrect"); } } catch (InvalidCipherTextException | RuntimeException e) { throw new GeneralSecurityException("encryption failed"); } // Return a base-64-encoded string containing IV + encrypted input string byte[] bytesAll = new byte[ivData.length + bytesEnc.length]; arraycopy(ivData, 0, bytesAll, 0, ivData.length); arraycopy(bytesEnc, 0, bytesAll, ivData.length, bytesEnc.length); out.println(new String(encodeBase64(bytesAll), UTF8)); return new String(encodeBase64(bytesAll), UTF8); }
From source file:labr_client.Public.encryption.java
License:Open Source License
/** * Decode a string which has first been encrypted with AES, and then * base64-encoded./*from w w w . j a v a 2 s . com*/ */ public static String decodeBase64Aes(String enc) throws GeneralSecurityException { byte[] bytesEnc = decodeBase64(enc.getBytes(UTF8)); // Extract the IV, which is stored in the next N bytes int nIvBytes = AES_NIVBITS / 8; byte[] ivBytes = new byte[nIvBytes]; arraycopy(bytesEnc, 0, ivBytes, 0, nIvBytes); // Select encryption algorithm and padding : AES with CBC and PCKS#7. // Note that the "encryption strength" (128 or 256 bit key) is set by the KeyParameter object. KeyParameter keyParam = getAesKey(); CipherParameters params = new ParametersWithIV(keyParam, ivBytes); BlockCipherPadding padding = new PKCS7Padding(); BufferedBlockCipher cipher = new PaddedBufferedBlockCipher(new CBCBlockCipher(new AESEngine()), padding); // Decrypt all bytes that follow the IV cipher.reset(); cipher.init(false, params); // first param = encode/decode byte[] bytesDec; try { int buflen = cipher.getOutputSize(bytesEnc.length - nIvBytes); byte[] workingBuffer = new byte[buflen]; int len = cipher.processBytes(bytesEnc, nIvBytes, bytesEnc.length - nIvBytes, workingBuffer, 0); len += cipher.doFinal(workingBuffer, len); // Note that getOutputSize returns a number which includes space for "padding" bytes to be stored in. // However we don't want these padding bytes; the "len" variable contains the length of the *real* data // (which is always less than the return value of getOutputSize. bytesDec = new byte[len]; arraycopy(workingBuffer, 0, bytesDec, 0, len); } catch (InvalidCipherTextException e) { throw new GeneralSecurityException("decode failed"); } catch (RuntimeException e) { throw new GeneralSecurityException("encryption failed"); } // And convert the result to a string out.println(new String(bytesDec, UTF8)); return new String(bytesDec, UTF8); }
From source file:my.adam.smo.common.SymmetricEncryptionBox.java
License:Open Source License
public byte[] encrypt(byte[] plainText, byte[] key) { if (key.length != 32) { throw new IllegalArgumentException("key have to be 32 bytes long (256 bits)"); }/*from w ww . j a v a 2s . c o m*/ byte[] seed = new byte[seedLength]; secureRandom.nextBytes(seed); byte[] seededPlainText = addSeedToMessage(plainText, seed); byte[] out = seededPlainText.clone(); byte[] iv = new byte[ivLength]; secureRandom.nextBytes(iv); CipherParameters cp = new ParametersWithIV(new KeyParameter(key), iv); PaddedBufferedBlockCipher encCipher; encCipher = new PaddedBufferedBlockCipher(new CBCBlockCipher(new AESFastEngine()), new ISO7816d4Padding()); encCipher.init(true, cp); encCipher.processBytes(seededPlainText, 0, seededPlainText.length, out, 0); return appendIV(out, iv); }
From source file:my.adam.smo.common.SymmetricEncryptionBox.java
License:Open Source License
public byte[] decrypt(byte[] cryptogram, byte[] key) { if (key.length != 32) { throw new IllegalArgumentException("key have to be 16 bytes long (32 bits)"); }/* w w w . j a v a2 s . com*/ byte[] out = Arrays.copyOfRange(cryptogram, ivLength, cryptogram.length); CipherParameters cp = new ParametersWithIV(new KeyParameter(key), getIV(cryptogram)); PaddedBufferedBlockCipher descCipher; descCipher = new PaddedBufferedBlockCipher(new CBCBlockCipher(new AESEngine()), new PKCS7Padding()); descCipher.init(false, cp); descCipher.processBytes(cryptogram, ivLength, cryptogram.length - ivLength, out, 0); return getMessageWithoutSeed(out); }
From source file:net.nharyes.secrete.curve.Curve25519PrivateKey.java
License:Open Source License
public static Curve25519PrivateKey deserialize(InputStream in, char[] password) throws IOException { try {/* www. j a v a 2s . c o m*/ // check magic number byte[] mn = new byte[MagicNumbers.PRIVATE_KEY.length]; IOUtils.readFully(in, mn, 0, mn.length); if (!Arrays.areEqual(mn, MagicNumbers.PRIVATE_KEY)) throw new IllegalArgumentException("Wrong key file format"); // read initial vector byte[] iv = new byte[16]; IOUtils.readFully(in, iv, 0, iv.length); // read salt byte[] salt = new byte[64]; IOUtils.readFully(in, salt, 0, salt.length); // initialize cipher CipherParameters params = new ParametersWithIV(new KeyParameter(deriveKey(password, salt)), iv); BufferedBlockCipher cipher = new PaddedBufferedBlockCipher(new CBCBlockCipher(new AESEngine()), new PKCS7Padding()); cipher.reset(); cipher.init(false, params); // decrypt key CipherInputStream cin = new CipherInputStream(in, cipher); byte[] key = new byte[Curve25519.KEY_SIZE]; IOUtils.readFully(cin, key, 0, key.length); // return key instance return new Curve25519PrivateKey(key); } catch (UnsupportedEncodingException ex) { throw new UnsupportedOperationException(ex.getMessage(), ex); } }
From source file:net.nharyes.secrete.curve.Curve25519PrivateKey.java
License:Open Source License
public void serialize(OutputStream out, char[] password) throws IOException { try {/*from w w w . j av a 2 s . c o m*/ // generate initial vector SecureRandom random = SecureRandom.getInstance("SHA1PRNG"); byte[] iv = new byte[16]; random.nextBytes(iv); // generate salt byte[] salt = new byte[64]; random.nextBytes(salt); // initialize cipher CipherParameters params = new ParametersWithIV(new KeyParameter(deriveKey(password, salt)), iv); BufferedBlockCipher cipher = new PaddedBufferedBlockCipher(new CBCBlockCipher(new AESEngine()), new PKCS7Padding()); cipher.reset(); cipher.init(true, params); // write magic number out.write(MagicNumbers.PRIVATE_KEY); out.flush(); // write initial vector and salt out.write(iv); out.write(salt); out.flush(); // write encrypted key to output stream ByteArrayOutputStream buf = new ByteArrayOutputStream(); CipherOutputStream cout = new CipherOutputStream(buf, cipher); cout.write(key); cout.close(); out.write(buf.toByteArray()); out.flush(); } catch (UnsupportedEncodingException | NoSuchAlgorithmException ex) { throw new UnsupportedOperationException(ex.getMessage(), ex); } }